返回查看(),并返回查看(新模型())之间的差异 [英] Difference between return View() and return View(new Model())

查看:124
本文介绍了返回查看(),并返回查看(新模型())之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道它的一个非常愚蠢的问题,但我有它有点混乱,因为我今天回答一个问题,我在提问的评论糊涂了。

I know its a very silly question, but i have a little confusion on it, as i was answering a question today, i got confused in the comment of the questioner.

如果我喜欢这个动作:

public Action Result Index()
{
return View();
}

和我的观点:

@model MyModel


@Html.TextBoxFor(x=>x.Name)

和如果我写的动作是这样的:

and if i write action like this:

public Action Result Index()
{
return View(new MyModel());
}

是这两个动作之间的区别,因为我不这样的话还可以查看被渲染过的空初始化模式。

what is the difference between these two actions, because i don't pass empty initialized model in that case also view is rendered.

我附上的链接,以及参考的问题在这里:
<一href=\"http://stackoverflow.com/questions/22971011/view-model-null-when-not-explicitly-passed-by-controller-to-strongly-typed-view/22971157?noredirect=1#comment35076325_22971157\">View型号空当没有明确的控制器传递到强类型的视图

I am attaching link as well of reference question its here: View Model Null when not explicitly passed by controller to strongly typed view

推荐答案

答案归结为如何拉姆达前pressions如

The answer comes down to how lambda expressions such as

x => x.Name

工作。最终,前pression不关心,如果你的模型
为空或不是因为它计算出如何通过渲染文本框
看定义的强类型类的属性
您已经定义了。

work. In the end, the expression does not care if your model is null or not as it figures out how to render the textbox by looking at the defined property of the strongly-typed class you have defined.

所以,如果你有类:

public class MyModel
{
public string Name {get; set;}
public int Age {get; set;}
.
.
.
}

,然后在你的教职员您引用您的模型像

and then in your veiw you reference your model like

@model MyModel

如果你看一下TextBoxFor源

If you look at the source of TextBoxFor

TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)

使用泛型类型。所以,既然你有一个强类型的视图

Generic types are used. So, since you have a strongly typed view with

@model MyModel

类型的TModel是为MyModel并与的HtmlHelper使用。此外

Type TModel is MyModel and used with the HtmlHelper. Also

Expression<Func<TModel, TProperty>> expression

是由以

Func<In TModel, Out TProperty> 

和因此前pression
可以与模型类型和属性类型的已知来评价。不要紧,你是否有模型的实际情况或没有。

and thus the expression can be evaluated with both the model type and property type known. It does not matter whether you have an actual instance of the model or not.

这篇关于返回查看(),并返回查看(新模型())之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆