MVC 3 DropDownListFor: Cannot figure out 'Syst

2019-07-25 17:45发布

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.

2条回答
ゆ 、 Hurt°
2楼-- · 2019-07-25 17:56

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"))
查看更多
\"骚年 ilove
3楼-- · 2019-07-25 18:19

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)
查看更多
登录 后发表回答