开发者

cant get Serialize HtmlHelper to work

i looked at : http://weblogs.asp.net/shijuvarghese/archive/2010/03/06/persisting-model-state-in-asp-net-mvc-using-html-serialize.aspx

but when i post the page the model(ie person) returns as null?

    [HttpPost]
    public ActionResult Edit([DeserializeAttribute]Person person, FormCollection formCollection)
    {

//this line has开发者_如何转开发 an error: TryUpdateModel(person, formCollection.ToValueProvider());

        return View(person);

    }


    <% using (Html.BeginForm("Edit", "Home"))
   {%>
<%=Html.Serialize("person", Model)%>
<%=Html.EditorForModel() %>
<button type="submit">
    go</button>
<%
    }%>

 [Serializable]
public class Person
{
    public string name { get; set; }
    public string suburb { get; set; }
}


Why you are trying to bind the person from the request using the following:

TryUpdateModel(person, formCollection.ToValueProvider());

when you explicitly know that there is no such thing in the request? This line invokes the model binder and tries to read it from the request values. But in your form you only have a single hidden field. So your action should look like this:

[HttpPost]
public ActionResult Edit([DeserializeAttribute]Person person)
{
    // Do something with the person object that's passed as
    // action argument
    return View(person);
}

Also your scenario looks strange. You have a view which seems to be strongly typed to this Person object in which you are using Html.EditorForModel meaning that you are offering the user possibility to edit those values. If you serialize the model you will get old values in your controller action. This attribute is only useful when you want to persist some model between multiple requests but there is no corresponding input fields in the form so that the default model binder can reconstruct the instance in the POST actions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜