How to fix conversion error in MVC2 dropdownlist

*爱你&永不变心* 提交于 2019-12-12 04:35:47

问题


I tried simple dropdownlist in ASP.NET MVC2 but got error below from tryupdatemodel.

How to fix this, everthing looks correct ?

view:

   <%= Html.DropDownList("Post24DeliveryPlaces", Model.DeliveryPlace)%>

model:

public IEnumerable<SelectListItem> Post24DeliveryPlaces { get; set; }

public string DeliveryPlace { get; set; }

result:

System.InvalidOperationException: The parameter conversion from type 'System.String' to type 'System.Web.Mvc.SelectListItem' failed because no type converter can convert between these types.  

at System.Web.Mvc.ValueProviderResult.ConvertSimpleType(CultureInfo culture, Object value, Type destinationType)  

 at System.Web.Mvc.ValueProviderResult.UnwrapPossibleArrayType(CultureInfo culture, Object value, Type destinationType)  

at System.Web.Mvc.ValueProviderResult.ConvertTo(Type type, CultureInfo culture)   at System.Web.Mvc.DefaultModelBinder.ConvertProviderResult(ModelStateDictionary modelState, String modelStateKey, ValueProviderResult valueProviderResult, Type destinationType

回答1:


The problem is that your html input is being named Post24DeliveryPlaces and it's trying to bind a single string to that.

The Post data is looking like this:

POST
{
    Post24DeliveryPlaces = (string)
}

However, in your model, Post24DeliveryPlaces is an IEnumerable and it can't convert at string to SelectListItem.

Html.DropDownList takes the field name as the first parameter. Try changing to this, giving the list of delivery places as the second parameter.

Html.DropDownList("DeliveryPlace", Model.Post24DeliveryPlaces)

This will generate the Html

<select name="DeliveryPlace">
    <option value="..">....</option>
    ....
</select>


来源:https://stackoverflow.com/questions/9218011/how-to-fix-conversion-error-in-mvc2-dropdownlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!