I have a Kendo grid with a custom edit button for each row. When a user clicks the edit button, a modal window opens where the user can edit the information and save the changes.
I've added an Editor Template to display a dropdownlist of state abbreviations.
StatesEditor.cshtml
@(Html.Kendo().DropDownList()
.Name("State")
.DataValueField("StateID")
.DataTextField("ShortName")
.BindTo((System.Collections.IEnumerable)ViewData["states"]))
This gets populated in my controller before I open my modal window:
public ActionResult OpenEditor([DataSourceRequest] DataSourceRequest request, int? addressId)
{
var address = db.Address.Where(x => x.AddressId == addressId).FirstOrDefault();
// code where I convert the address to an AddressMetadata
// ...
// ...
ViewData["states"] = ACore.Methods.ViewDataPopulation.PopuldateStates();
return PartialView("~/Views/System/Addresses/AddressEditorPopup.cshtml", addr);
}
In my view I have
@Html.EditorFor(model => model.State)
and this is my model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace ACore.Models
{
[MetadataType(typeof(AddressMetadata))]
public partial class Address
{
}
public class AddressMetadata
{
public int AddressID { get; set; }
public string Street1 { get; set; }
public string Street2 { get; set; }
public string City { get; set; }
[UIHint("StatesEditor")]
public State State { get; set; }
public string ZipCode { get; set; }
}
}
and this is my States model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ACore.Models
{
public class State
{
public int Id { get; set; }
public string ShortName { get; set; }
}
}
The dropdownlist is being populated with a list of the states but it is set to "AK", the first state in the list. I'm passing my view a model where the state is to a State Model with an Id of 41 and a ShortName of "SC".
How can I get my dropdownlist to be set to the state I'm passing in?
UPDATED:
I don't know if this is the correct way to do this but this is how I fixed it. Just adding the SelectedIndex fixed the issue but I added the code above the DropDownList so I could use this editor in other places where I wasn't passing in the Id.
@model ACore.Models.State
@{
var modelId = 0;
}
@if (Model != null)
{
modelId = Model.Id - 1;
}
@(Html.Kendo().DropDownList()
.Name("State")
.DataValueField("StateID")
.DataTextField("ShortName")
.SelectedIndex(modelId)
.BindTo((System.Collections.IEnumerable)ViewData["states"])
)
I've answered my question in my updated comments above. I would still like to know if this is the recommended way to do this.
@model ACore.Models.State
@{
var modelId = 0;
}
@if (Model != null)
{
modelId = Model.Id - 1;
}
@(Html.Kendo().DropDownList()
.Name("State")
.DataValueField("StateID")
.DataTextField("ShortName")
.SelectedIndex(modelId)
.BindTo((System.Collections.IEnumerable)ViewData["states"])
)