【发布时间】:2020-04-05 20:27:52
【问题描述】:
我想将 user.Id 传递给局部视图以在局部视图中填充 @Html.EditorFor(model => model.UserID, new { @Value = id })。我在这个局部视图模型中得到了空值。
父视图的代码是:
@model KhanewalNews.Models.user
@{
int id = Model.id;
}
@Html.Partial("AssignRoles",null, new ViewDataDictionary { { "id", id } });
@{
ViewBag.Title = "MemberDetails";
Layout = "~/Views/Shared/_DashboardLayout.cshtml";
}
//parent view implementation here
部分视图的代码是:
@model KhanewalNews.Models.Role
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
@{
int id = (int)this.ViewData["id"];
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.UserID)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UserID, new { @Value = id })
@Html.ValidationMessageFor(model => model.UserID)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.role1)
</div>
<div class="editor-field">
@Html.DropDownListFor(m => m.role1, new SelectList(
new List<Object>{
new { value = "add" , text = "add" },
new { value = "update" , text = "update" },
new { value = "delete" , text = "update"},
new { value = "super" , text = "super"}
},
"value",
"text"
))
@Html.ValidationMessageFor(model => model.role1)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
这会引发异常
System.NullReferenceException: '对象引用未设置为对象的实例。'
在局部视图中。
请指导我哪里错了。
控制器:
public ActionResult AssignRoles()
{
return View();
}
[HttpPost]
public ActionResult AssignRoles(Role r)
{
//implementation here
return View();
}
public ActionResult MemberDetails(int id)
{
var userdetail = new user();
var user = db.users.Where(x => x.id == id).FirstOrDefault();
userdetail.username = user.username;
return View(userdetail);
}
【问题讨论】:
-
如果只将 UserID 传递给部分,那么部分页面中的其他属性呢?他们是否抛出空引用异常?尝试删除部分页面中的其他模型属性以识别究竟是什么。
-
是的,我做了:@Html.Partial("AssignRoles",null, new ViewDataDictionary { { "id", id } });但收到 null。
-
你调试了吗?您确定 id 为 null 还是您的角色部分视图中的模型?
-
@JerdineSabio 谢谢,在调试时我发现 id 不为空。问题出在我的控制器上,我发送的用户模型不完整。这段代码现在可以正常工作了。
标签: c# asp.net-core-mvc asp.net-mvc-partialview