Reputation: 373
I am using Kendo Combo Box in my view. I bind this combo box to a Enum type in my model. But when I run application and change the values in drop down. Always only the first value is selected and passed to the model.
//MyModel
public class Mymodel
{
public IsPerson IsPerson { get; set; }
}
public enum IsPerson
{
yes,
No
}
//index.cshtml
@(Html.Kendo().ComboBoxFor(x => x.MyModel.IsPerson )
.Name("IsPerson ")
.Placeholder("Select IsPerson ..")
.BindTo(Enum.GetNames(typeof(App2_MVC.Models.IsPerson))))
what is the reason? Even if I select "No" in dropdown I am getting selected item as '0' so value 'Yes'??
Upvotes: 0
Views: 6926
Reputation: 1086
Instead of binding the combo box to enum bind it to object of key, value pair. Also define the "DataTextField and DataValueField" to get proper value of selected element.
@(Html.Kendo().ComboBoxFor(model => model.IsPerson)
.Placeholder("----- Select -----")
.DataTextField("Value")
.DataValueField("Key")
.DataSource(source => source.Read(read => read.Action("MyActionMethod", "Controller")))
)
Action method should return IEnumerable< Model > object where "Model" is of "Key and value" pair. i.e.
public class Model
{
public string Value{ get; set; }
public int Key{ get; set; }
}
In controller:
public ActionResult MyActionMethod()
{
var model= new Model
{
Value = "xyz",
Key = 1
};
var selectList = new List<Model>();
selectList.Add(model);
// Also can add multiple objects
// Or add your database code to fetch the values from db table
return Json(result, JsonRequestBehavior.AllowGet);
}
As per Your code:
@model myapplication.Models.MyDetails
<div>
@using (Html.BeginForm("PostMymethod", "Home", FormMethod.Post))
{
@(Html.Kendo().PanelBar()
.Name("Intro")
.ExpandAll(false)
.ExpandMode(PanelBarExpandMode.Single)
.Items(items =>
{
items.Add()
.Text("Jquery")
.Content(@<text>
@(Html.Kendo().DropDownListFor(x => x.sismember)
.DataTextField("value")
.DataValueField("key")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("MyActionMethod", "Home");
});
})
)
</text>);
})
)
<table>
<tr>
<td class="savebtns">
<input type="submit" name="Command" value="Save" id="savebtn" class="=btn" />
</td>
</tr>
</table>
}
</div>
Model Property:
public class MyDetails
{
public string sismember { get; set; }//this is the property im binding to combobox
}
where Ismember is a class which has key and value:
public class IsMember
{
public string value { get; set; }
public int key { get; set; }
}
I want to get seleted combox value in this controller : MyController
public class HomeController : Controller
{
[HttpPost]
public ActionResult PostMymethod(MyDetails myDataModel,string command)
{
if (command == "Save")
{
return View("Home", myDataModel);
}
return View("Home", myDataModel);
}
}
Upvotes: 4