Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.NET MVC中的DropDownList for和TryUpdate模型_C#_Asp.net Mvc_Razor - Fatal编程技术网

C# ASP.NET MVC中的DropDownList for和TryUpdate模型

C# ASP.NET MVC中的DropDownList for和TryUpdate模型,c#,asp.net-mvc,razor,C#,Asp.net Mvc,Razor,我有两个相关的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;} } 这样,如果用户选择“无/未知”,则控制器中父对象的子值为空,但如果用户选择任何其

我有两个相关的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;}
}
这样,如果用户选择“无/未知”,则控制器中父对象的子值为空,但如果用户选择任何其他值(即从数据库检索的子对象的ID),则实例化父对象的子值并用该ID填充

基本上,我正在努力解决如何跨HTTP无状态边界保存一个可能的实体列表,以便其中一个实体被正确地重新水化,并通过默认的模型绑定器进行分配。我是不是要求太多了

我是不是要求太多了

是的,你要求的太多了

POST请求发送的所有内容都是所选实体的ID。别指望能得到更多。如果您想重新水化或其他什么,您应该查询您的数据库。与GET操作中填充子集合的方式相同

哦,您的POST action=>有一个问题,您两次调用默认的模型绑定器

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

或:

在您的代码中,您混合了这两种情况,这是错误的。基本上是两次调用默认模型绑定器

<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);
}
[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);
}