【发布时间】:2023-03-09 19:35:01
【问题描述】:
这有点令人困惑。直到今天我才知道以下在 MVC 中传递数据以查看的方法 ViewBag、ViewData、TempData、强类型视图及其模型。 因此,无论我们在哪里使用强类型视图,我们都会将带有数据或空对象的模型传递给视图,这样它就不会抛出任何空引用错误。
但是今天遇到了一个让我觉得奇怪的行为。
案例一
以下是EmployeeController的Create动作
//
// GET: /Employee/Create
public ActionResult Create()
{
return View("Create");
}
以下是员工文件夹或视图中的 CreateView。
@model EmployeeDataBase.Models.Employee
<fieldset>
<legend>Employee</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
我没有在动作中返回任何模型,但视图仍然被渲染。
案例 2
我的行动
public ActionResult Create(Employee employee, Employee emp)
{
return View("Create");
}
使用以下 URL 调用上述方法
http://localhost:50128/Employee/Create?Name=something
操作中的两个 Employee 参数均使用 Name 属性值作为“某物”实例化。在动作中没有返回任何东西,仍然创建渲染。如果在调试过程中动态改变 Name 的值,它仍然会在 Name 文本框的 Create 视图中显示“something”。
【问题讨论】:
-
Q1:HtmlHelpers 使用
@model语句中定义的模型的ModelMetadata,因此模型可以是null(但建议您始终将模型传递给视图。 -
Q2:不清楚您的要求,但 GET 方法通常不应将模型作为参数。您的模型有一个属性
string Name,并且它的值已添加到ModelState,HtmlHelpers 使用它来生成value属性。 -
@Ravi 下面的答案是否回答了您的问题?如果是,请阅读this
标签: c# asp.net-mvc asp.net-mvc-4 model-binding strongly-typed-view