这有点让人困惑。直到今天,我还知道以下在MVC ViewBag、ViewData、TempData、强类型视图及其模型中传递数据到视图的方法。因此,无论我们在何处使用强类型视图,我们都会将带有数据或空对象的模型传递给视图,这样它就不会抛出任何空引用错误。
但今天遇到了一种让我感到奇怪的行为。
案例-1
以下是EmployeeController的创建操作
//
// 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参数都被实例化,其名称属性值为“the”。在操作中没有返回任何内容,仍然呈现创建。如果在调试期间动态更改名称的值,则它仍会在“名称”文本框中的“创建”视图中显示“某些内容”。
发布于 2016-03-22 11:31:40
案例1:
如果您将一个模型传递到视图中,它就会显示该模型。如果不传递模型,视图只使用模型类创建控件。在这种情况下,它正在为所有属性创建标签、文本框和验证。它使用LabelFor (xxxFor)中的lambda表达式作为表达式树,并分析类。它分析并查找如下内容:在模型中,您可能对Name属性使用了显示(“全名”)属性,因此它将得出您希望在标签中而不是在“名称”中显示“全名”的结论。它以同样的方式创建验证javascript。
因此,为了使用lambdas中给出的表达式树,它不需要模型的实例。
案例2:
在this中已经有了这样的问题。
https://stackoverflow.com/questions/36152727
复制相似问题