开发者

Way to avoid FormCollection for ASP.NET MVC?

I'm very noob when it comes to ASP.NET MVC.

I'm looking at the starter example from the ASP.NET MVC add-in.

I see something like this was automatically generated:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
    try
    {
        // TODO: Add update log开发者_StackOverflow社区ic here
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

I find this stinks because I want to use the Entity Framework where entity state will be conserved. I would like something similar to:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Person person)
{
    try
    {
        // TODO: Add update logic here
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

Notice I took out FormCollection and replaced it with the Person class. - I would like this to avoid magic strings. - Conserve entity states. - More explicit.

Is this even possible?

/confused with MVC


Yes, this is possible! The elements of your form will need to have the same name as the properties of the model that you're trying to represent. This process is referred to as Binding, and you can discover more if you look at the ModelBinder object.

For more infos, take a look at this question: ASP.NET MVC example of editing multiple child records.


Yes, although I strongly recommend using dedicated presentation/edit models instead of using your entities. Nonetheless, what you show will work, if there's enough info in your form to populate all non-nullable properties of Person.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜