繁体   English   中英

ASP.NET MVC中的DropDownListFor和TryUpdateModel

[英]DropDownListFor and TryUpdateModel in ASP.NET MVC

我有两个相关的POCO

public class Parent
{
   public Guid Id {get; set;}
   public IList<Child> ChildProperty {get; set;}
}

public class Child
{
   public Guid Id {get; set;}
   public String Name {get; set;}
}

我有一个.cshtml Razor视图,

<div>
    @{
        var children =
            new SelectList(Child.FindAll(), "Id", "Name").ToList();
    }
    @Html.LabelFor(m => m.Child)
    @Html.DropDownListFor(m => m.Child.Id, , children, "None/Unknown")
</div>

我想在控制器类中执行以下操作:

[HttpPost]
public ActionResult Create(Parent parent)
{
    if (TryUpdateModel(parent))
    {
        asset.Save();
        return RedirectToAction("Index", "Parent");
    }

    return View(parent);
}

这样,如果用户选择“无/未知”,则控制器中父对象的子值为空,但是如果用户选择任何其他值(即从数据库中检索到的子对象的ID),则子对象的值实例化父对象,并使用该ID进行填充。

基本上,我在为如何在HTTP无状态边界上保留可能的实体列表而苦苦挣扎,以便通过默认模型绑定器正确地对其中一个实体进行补水和分配。 我只是要求太多吗?

我只是要求太多吗?

是的,您要求太多。

与POST请求一起发送的所有内容就是所选实体的ID。 不要期望得到更多。 如果要补充水分或其他任何内容,都应查询数据库。 与您在GET操作中填充子集合的方式相同。

哦,您的POST动作有问题=>您要两次调用默认模型绑定程序。

这是2种可能的模式(我个人更喜欢第一种,但是在某些情况下,当您要手动调用默认模型绑定程序时,第二种可能也很有用):

[HttpPost]
public ActionResult Create(Parent parent)
{
    if (ModelState.IsValid)
    {
        // The model is valid
        asset.Save();
        return RedirectToAction("Index", "Parent");
    }

    // the model is invalid => we must redisplay the same view.
    // but for this we obviously must fill the child collection
    // which is used in the dropdown list
    parent.ChildProperty = RehydrateTheSameWayYouDidInYourGetAction();
    return View(parent);
}

要么:

[HttpPost]
public ActionResult Create()
{
    var parent = new Parent();
    if (TryUpdateModel(parent))
    {
        // The model is valid
        asset.Save();
        return RedirectToAction("Index", "Parent");
    }

    // the model is invalid => we must redisplay the same view.
    // but for this we obviously must fill the child collection
    // which is used in the dropdown list
    parent.ChildProperty = RehydrateTheSameWayYouDidInYourGetAction();
    return View(parent);
}

在您的代码中,您将两者混合在一起是错误的。 您基本上是在两次调用默认模型联编程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM