如何在ASP.NET MVC POST请求之间传输的数据视图模型?

编程入门 行业动态 更新时间:2024-10-27 22:30:54
本文介绍了如何在ASP.NET MVC POST请求之间传输的数据视图模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个视图模型像这样:

I have a ViewModel like so:

public class ProductEditModel { public string Name { get; set; } public int CategoryId { get; set; } public SelectList Categories { get; set; } public ProductEditModel() { var categories = Database.GetCategories(); // made-up method Categories = new SelectList(categories, "Key", "Value"); } }

然后我有一个使用这个模型中的两个控制器的方法:

Then I have two controller methods that uses this model:

public ActionResult Create() { var model = new ProductEditModel(); return View(model); } [HttpPost] public ActionResult Create(ProductEditModel model) { if (ModelState.IsValid) { // convert the model to the actual entity var product = Mapper.Map(model, new Product()); Database.Save(product); return View("Success"); } else { return View(model); // this is where it fails } }

第一次用户进入到创建视图,它们都带有类别列表。但是,如果他们无法验证,查看发送回给他们,不过这次的类别属性为null。这是可以理解的,因为 ModelBinder的不会保留类别如果在POST请求没有。我的问题是,什么是保持最好的方法类别坚持?我可以做这样的事情:

The first time the user goes to the Create view, they are presented with a list of categories. However, if they fail validation, the View is sent back to them, except this time the Categories property is null. This is understandable because the ModelBinder does not persist Categories if it wasn't in the POST request. My question is, what's the best way of keeping Categories persisted? I can do something like this:

[HttpPost] public ActionResult Create(ProductEditModel model) { if (ModelState.IsValid) { // convert the model to the actual entity var product = Mapper.Map(model, new Product()); Database.Save(product); return View("Success"); } else { // manually populate Categories again if validation failed model.Categories = new SelectList(categories, "Key", "Value"); return View(model); // this is where it fails } }

但是,这是一个丑陋的解决方案。我还能如何坚持呢?因为它是一个集合我不能使用隐藏域。

But this is an ugly solution. How else can I persist it? I can't use a hidden field because it's a collection.

推荐答案

我通常会实现我的列表(下拉菜单)为只读属性。当查看获得的财产被包含在它所需要返回值的自我价值。

I typically implement my lists (for drop downs) as a readonly property. When the View gets the value the property is self contained on what it needs to return the values.

public SelectList Categories { get { var categories = Database.GetCategories(); // made-up method return new SelectList(categories, "Key", "Value"); } }

如果有必要,你可以抓住当前选择的项目(即验证含有被张贴并绑定到你的类的实例ID属性失败)。

If necessary you can grab the currently selected item (i.e. validation failed) from the property containing the id that was posted and bound to the instance of your class.

更多推荐

如何在ASP.NET MVC POST请求之间传输的数据视图模型?

本文发布于:2023-11-16 08:17:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1602563.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   模型   数据   如何在   ASP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!