开发者

Persistant model data in ASP.NET MVC

I have two controller function开发者_JAVA百科s: one for default viewing, and one for postback. The first one I use to assign some default values to the model's list. The second is to add additional values to the list. After either, the page displays the list's contents. Right now, I'm losing everything in the list except what the latest controller function did.

I'd like my model data to persist, how can this be done?


I suppose you have a situation like this:

public class Model {
  public List<..> List { get; set; }
  ...
}

public class MyController 
{
  public ActionResult List() {
    return View(new Model { List = new List<..> { /* some items */ } });
  }

  [HttpPost]
  public ActionResult AddToList(Model model, string itemText) {
    model.List.Add(/* another item with specified text*/);
    return View("List", model);
  }
}

In the displayed list page you either have a 1 item added with the AddToList action or the entire list of items initialized in the List action. What happens is natural, because you don't post the list back.

If this is the case, then you have to post back the entire model, including the list itself in order to add an item to the existing list.

This is really a problem of generating the correct View for the List page. The form that triggers the AddToList action must contain the date of the entire model/list. The HTML generated by the view should look something like this:

...
<form method="POST" action="/MyController/AddToList">
   <input type="hidden" name="model.List[0]" value="value1" />
   ...
   <input type="hidden" name="model.List[N]" value="valueN" />
   New item text: <input type="text" name="itemText" />
   ...
</form>
...


Persist your data in database(use EF(http://msdn.microsoft.com/en-us/library/bb399572.aspx)).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜