MVC 3 DropDownListFor: Cannot figure out 'System.Web.Mvc.SelectList' cannot be serialized

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-05 09:03:17

问题


I cannot figure out how to do serialization with a DropDownList and am getting the error "Type 'System.Web.Mvc.SelectList' cannot be serialized." I am using serialization in a wizard form to persist the user inputs through the end and then to post a confirmation.

I am using the following in a view:

@using (Html.BeginFormAntiForgeryPost())
{ 
    @Html.Hidden("myData", new MvcSerializer().Serialize(Model, SerializationMode.Signed))
    ...
    @Html.DropDownListFor(m => m.RealEstate, Model.RealEstateList)
    ...
}

In my ViewModel (MyData), I have:

[Serializable]
public class myData
{
public int RealEstate { get; set; }
public IEnumerable<SelectListItem> RealEstateList { get; set; }
...
public MyData()
    {
        var realestatelist = new List<SelectListItem>() {
            new SelectListItem { Text = "(Please select)" },
            new SelectListItem { Value = "1", Text="Some text." },                
            new SelectListItem { Value = "2", Text="Some other text." }
            };
        this.RealEstateList = new SelectList(realestatelist, "Value", "Text");
    }
}

Any help is greatly appreciated.


回答1:


The SelectList does not support serialization. Try to use IEnumerable<SelectedListItem>, IList<SelectListItem> or List<SelectedListItem> in your controller and then create the SelectList in the view.

Change controller similar to this:

public MyData()
    {
        var realestatelist = new List<SelectListItem>() {
            new SelectListItem { Text = "(Please select)" },
            new SelectListItem { Value = "1", Text="Some text." },                
            new SelectListItem { Value = "2", Text="Some other text." }
            };
        this.RealEstateList = realestatelist;
    }
}

And seeing your RealEstateList in the model is already IEnumerable<SelectListItem> you can make the SelectList in the view then to specify the value and text without converting the model property like this:

@Html.DropDownListFor(m => m.RealEstate, new SelectList(Model.RealEstateList, "Value", "Text"))



回答2:


The SelectList class can't be serialized, as the error is saying. If you need to serialize a set of SelectListItem objects you'll need to use a container that can be serialized, like a List<SelectListItem>.

You will need to convert your List<SelectListItem> back into a SelectList inside your view, like:

@{
    var bindList = new SelectList(Model.RealEstateList);
}

@Html.DropDownListFor(m => m.RealEstate, bindList)


来源:https://stackoverflow.com/questions/9214918/mvc-3-dropdownlistfor-cannot-figure-out-system-web-mvc-selectlist-cannot-be-s

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