in the aspx page i am getting this error while binding dropdown list
Unable to cast object of type
'System.Web.Mvc.SelectList' to type
'System.Collections.Generic.IList`1[System.Web.Mvc.SelectListItem]'.
I have written:
<p>
<label for="categoryId">Category:</label>
<%= Html.DropDownList("categoryId", (IList<SelectListItem>)ViewData["categoryId"])%>
<%= Html.ValidationMessage("categoryId", "*")%>
</p>
please tell me the correct way of writing.
thanks
ritz
Here is a nice example of exactly what you are trying to accomplish:
How to bind IList with MVC Dropdownlist box
It looks like you will have to add some code-behind code to build the compatible list type.
what is the code in the controller action that you use to generate viewdata["categoryId"], here is what i normally do in the action code:
ArrayList categoryList=New ArrayList;
foreach (category c In YourcategoryCollection)
{ categoryList.Add(New With {.Item = c.categoryName, .value = c.categoryID})
}
Viewdata("categoryId")=New SelectList(categoryList, "Value", "Item", itemToEdit.categoryID)}
and then in your view, you just need:
<%= Html.DropDownList("categoryId", ViewData["categoryId"])%>
Related
I am working on a Asp.net MVC 2.0 web application. In my form , i have non editable fields , so i wanted to display them as labels rather than textboxes.
I am strongly binding my model with view. So, i need to associate this label with one of the fields in model.
This is what i am trying to do:
<%=html.LabelFor(model=>model.changedby)%>
<%=html.DisplayFor(model=>model.changedby,XYZ)%>
But, it is displaying nothing..Please help
Updated2:
What basically i am trying to do is a add operation. i have a create view and that view has a form.
I am strongly binding this view with model.So , that i can directly associate form fields with the model Properties.
Ex:
<label> Name</label> <%=Html.TextBoxFor(m=>m.name)
So, what ever i type into the textbox , it will be stored in m.name in the model.
If the text entered is "Avinash" , then m.name gives value "Avinash"
I think i am correct upto this extent:
Similarly..
I have a field which is readonly , the user can not change the value of it.
<label>Changed On</label> <label> DateTime.Now </label>
How to bind m.ChangedOn with the labels values(DateTme.Now)
so that it will result in m.Changedon as DateTime.now
Updated3:
This is what i am writing..
<td >
<%=Html.LabelFor(Model=>Model.CreatedOn) %>:
</td>
<td>
<%=Html.HiddenFor(Model=>Model.CreatedOn) %>
</td>
You no need to wrap with <label>, since MVC LabelFor will automatically create those html tags for you
So change this
<label>
<%=html.LabelFor(model=>model.changedby)%>
</label>
to
<%= Html.LabelFor(model=>model.changedby) %>
Update:
If you want to send the data to the server while you post your form, make sure you have a data in a form fields. Only form fields like input,select,textarea are posted to server and not display tag value like label, span, div, etc
Still if you need to post the label value, you can use hidden with it
<%= Html.LabelFor(model=>model.changedby) %>
<%= Html.HiddenFor(model=>model.changedby) %>
If you have both, your hidden field will posted to server, which contains the same value
Controller code
public ActionResult Index()
{
MyviewModel model=new MyviewModel();
model.ChangedOn=DateTime.Now;
return View(model);
}
For Save
public ActionResult Save(MyviewModel model)
{
model.ChangedOn; // this property will show you hidden value
//If you need current time, since the rendered time was old. Its good to assign like below
//model.ChangedOn=DateTime.Now
}
use this
<%= Html.DisplayFor(model => model.changedby) %>
I have this function that returns the type IEnumerable<SelectListItem>.
public IEnumerable<SelectListItem> GetItems()
{
IEnumerable<SelectListItem> results = null;
results =*(some logic)*
return results;
}
I try to bind this to dropdown in a view using
<% foreach (IEnumerable<SelectListItem> schdItem in Model.GetItems())
{%>
<%= Html.DropDownList("xxx", schdItem)%>
<%} %>
But it breaks with the error message
Unable to cast object of type 'System.Web.Mvc.SelectListItem' to type 'System.Collections.Generic.IEnumerable`1[System.Web.Mvc.SelectListItem]'.
How do I fix this?
Based on the comment from asawyer I modified it to
<%= Html.DropDownList("xxx", Model.GetScheduleItems())%>
now it works!
No loop needed, just this.
<%= Html.DropDownList("xxx", Model.GetItems())%>
I would make the SelectList a property on your model rather than a getter method.
<%= Html.DropDownList("xxx", Model.MySelectList)%>
<%= Html.DropDownList("xxx", Model.GetItems())%>
Althought this is a terrible way to go about it. Instead, you should be using Html.DropDownListFor such as this:
<%= Html.DropDownListFor(Model.SelectedItem, Model.Items) %>
Where Model.SelectedItem is the type of item, and Model.Items is a property that returns a collection of SelectListItems.
I have the following form:
<li>
<% using (Html.BeginForm("TestMethod", "MyController", FormMethod.Post, new {id = "TestMethod"}))
{%>
<%= Html.Hidden("model", Model.MyListOfObjects) %>
<%}%>
Test
</li>
And the javascript function for the onclick is as follows:
function SubmitForm() {
document.forms["TestMethod"].submit();
}
I am trying to pass the list of objects from the view into the controller, but i have yet managed to get this to work. My Controller function is:
[Authorize]
[HttpPost]
public ActionResult TestMethod(List<Objects> model)
{
dynamic Expando = new ExpandoObject();
Expando.test = model;
return View(Expando );
}
When I view the List of objects in the debugger it always displays "System.Collections.Generic.List`1[]" with no actual objects inside.
So my question is what should I be doing to pass a List of objects into a controller?
I have also tried:
<% using (Html.BeginForm("TestMethod", "MyWork", FormMethod.Post, new {id = "TestMethod"}))
{%>
<% int itemx = 0; %>
<% foreach (var x in Model.MyListOfObjects)
{%>
<%= Html.Hidden("model"+"["+itemx+"]", x) %>
<%itemx++; %>
<% } %>
<%}%>
You cannot just put List<object> as action parameter and expect the model binder to be able to automagically guess what object types you want to put there. You will need to write a custom model binder if you wanted to handle multiple sub-types as illustrated in this post.
And if you want to use a single type for the list such as List<MyViewModel> then simply loop through each element of the list (respecting the convention) and for each element build a hidden field for each property that you want to bind.
But since those are hidden fields, I guess that the user is not supposed to modify them. In this case those hidden fields have nothing to do in your view. Let's not reinvent the ViewState that we were all so happy to get rid of when we moved to ASP.NET MVC from classic WebForms. Simply put a hidden field containing an unique id that will allow you to refetch the corresponding list elements in the POST action given this unique id from wherever you fetched them initially (your database or something I suppose).
You need to have one hidden element for each object in the list, and named model[0], model[1], etc.
I have a dropdownlist that I populate with some stuff:
In my controller
ViewData["SourceModelList"] = new SelectList(_modelService.GetAllModels(), "Id", "Description");
in my view
<% using (Html.BeginForm("Compare", "Home")) { %>
<p>
<%=Html.DropDownList("SourceModelList")%>
</p>
<p>
<input type="submit" value="Compare" />
</p>
<% } %>
And this renders lovely. Now when I post back to my 'compare' action, how do I find out which item was selected in the drop down?
The name "SourceModelList" should correspond with the name of a field in your ViewModel, so that the binder has something to bind the value of the dropdown to.
Alternatively, you can pluck the value out of the FormCollection object, if your view is not strongly-typed.
The NerdDinner Tutorial goes into this process in greater detail:
NerdDinner Step 5: Create, Update, Delete Form Scenarios
http://nerddinnerbook.s3.amazonaws.com/Part5.htm
You can use any of the regular methods for getting items from a form in ASP.NET MVC: FormCollection, Request object, binding to a specific model or having an action which takes a string SourceModelList parameter.
You can do:
int value = Convert.ToInt32(Request.Form["SourceModelList"]);
Or by ModelBinders just making sure that your model have a property
public int SourceModelList {get; set;}
And the ModelBinder will get it for you.
Or, but less likely:
public ActionResult Name(FormCollection f, int SourceModelList)
Can somebody give me an sample code to retreive the item from html.dropdownlist?
Suppose that you have this DropDown in the view:
<p><label for="ProductType">Product Type:</label>
<br /><%=Html.DropDownList("ProductTypeDropDown",
New SelectList(ViewData("ProductTypes"),
"ProductTypeID", "Name"))%>
</p>
You can simple retrieve the selected value in the controller using
Product.ProductType = form("ProductTypeDropDown")