Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/17.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 2中验证失败时,保留对象列表并将其传递给“创建/编辑”视图_C#_Asp.net Mvc_Validation_Foreign Keys - Fatal编程技术网

C# 在ASP.NET MVC 2中验证失败时,保留对象列表并将其传递给“创建/编辑”视图

C# 在ASP.NET MVC 2中验证失败时,保留对象列表并将其传递给“创建/编辑”视图,c#,asp.net-mvc,validation,foreign-keys,C#,Asp.net Mvc,Validation,Foreign Keys,我正在绑定模型中的外键属性。我正在传递模型中该属性的可能值列表。模型的外观如下所示: public class UserModel { public bool Email { get; set; } public bool Name { get; set; } public RoleModel Role { get; set; } public IList<RoleModel> Roles { get; set; } } public class

我正在绑定模型中的外键属性。我正在传递模型中该属性的可能值列表。模型的外观如下所示:

public class UserModel
{
    public bool Email { get; set; }
    public bool Name { get; set; }
    public RoleModel Role { get; set; }
    public IList<RoleModel> Roles  { get; set; }
}

public class RoleModel
{
    public string RoleName
    {
        get;
        set;
    }
}
如上面的评论所述,我需要将带有角色列表的模型再次传递给我的视图,但是model.roles为null。目前,我再次向服务请求角色模型;但是我不想在已经从DB获取列表的情况下增加额外的开销


有人知道怎么做吗?

您可以将其存储在TempData中

TempData["UserRoles"] = Model.Roles;

也就是说,我倾向于避免在请求之间保留数据。认真地问问自己,返回数据库会耗费多少精力。

理想情况下,我希望在请求之间保留的集合将以与使用http参数的模型其余部分相同的方式传递。我只是想知道是否有可能做到这一点,可能是使用MVC2 Futures视图状态特性将数据序列化到,然后使用model binder对其进行反序列化,或者使用JSON进行序列化。这样做会更干净,不是吗?稍后我会做一些测试并发布结果。为什么要将数据作为表单的一部分传递给客户端?我的意思是你可以-只使用一个隐藏字段-但我不明白为什么你会想要towell,因为它位于管理区域,而且不会经常使用,我会接受再次从DB获取结果的小开销。
<div class="editor-label">
        <%= Html.LabelFor(model => model.Role) %>
</div>
<div class="editor-field">
    <%= Html.DropDownListFor(model => model.Role, new SelectList(Model.Roles, "RoleName", "RoleName", Model.Role))%>
    <%= Html.ValidationMessageFor(model => model.Role)%>
</div>
[HttpPost]
public ActionResult Create(UserModel model)
{
    if (ModelState.IsValid)
    {
        // insert logic here
    }
    //the validation fails so I pass the model again to the view for user to update data but model.Roles is null :(
    return View(model);
}
TempData["UserRoles"] = Model.Roles;