开发者

Asp.Net MVC Not Duplicate forms when Edit/Add

When we have anything that requires user input (Eg adding a product to a database) the Edit screen looks the s开发者_C百科ame as the add screen. When using MVC .Net how do you handle this? Do you return the same view? Just adjust the model to reflect the change?


Same (partial)view

You create only one but strong typed view (depending on the UI it can of course be a partial view as well). When adding new data return this view from controller action with default model object instance (usually just a new instance without any properties being set), but when you edit, return it with the object instance that you'd like to edit.

Controller part

Regarding controller actions you can have four of them:

  1. Add GET
    return View("SomeView", new Customer());
  2. Add POST
  3. Edit GET
    return View("SomeView", new CustomerRepository().GetCustomer(id));
  4. Edit POST

Bot GET actions return the same view but with different model as described earlier. POST actions both store submitted data, but return whatever they need to. Probably some RedirectToAction()...


You can use the same view for display and Edit, simply call it from your controller

return View("ViewName")


You could have the form fields in a partial view and have two separate views using the same partial view, one posting to the edit controller action method and the other posting to the add controller action method.


Partial views are used to remove duplicity. You could read an example of this in the Nerd Dinner tutorial.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜