Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

c# - How to fix conversion error in MVC2 dropdownlist

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...