简体   繁体   English

为要传递给Partial View的模型设置默认值

[英]Set a default value to the model being passed to Partial View

I have a partial view that is called from another partial view (kind of nested partial views). 我有一个局部视图,从另一个局部视图(一种嵌套的局部视图)调用。

The outer partial view is called Company and the inner partial view is a custom control called searchHelp. 外部局部视图称为Company,内部局部视图是名为searchHelp的自定义控件。 Both accept a parameter. 两者都接受参数。

Now the Company view gets a parameter of type company and searchHelper accepts an optional string. 现在,Company视图获取了company类型的参数,searchHelper接受可选字符串。 This part works fine as I am testing the model value for null and assigning is default text as @((Model==null)?"Enter Text":Model) when used in other views even without passing a parameter. 这部分工作正常,因为我正在测试null的模型值,并且当在其他视图中使用时,即使不传递参数,也将默认文本分配为@((Model==null)?"Enter Text":Model)

In my case of nested views, if I dont provide a string as model for searchHelper then it takes company as model from the outer view ie company and gives an error. 在我的嵌套视图的情况下,如果我不提供字符串作为searchHelper的模型,那么它将company作为外部视图即公司的模型并给出错误。

The @model definition is not a value setter, it's merely telling Razor what type of view to instantiate. @model定义不是值设置器,它只是告诉Razor实例化什么类型的视图。 You can't define a default value here. 您无法在此处定义默认值。 If you don't pass a model to your partial, then it will use the model of the parent view, which is Company in this case. 如果您没有将模型传递给partial,那么它将使用父视图的模型,在这种情况下是Company Company is not a string, obviously, so you get that error. 显然, Company不是字符串,所以你得到了这个错误。 If you want to pass a default value for the partial, do that in the second parameter to Html.Partial : 如果要为partial传递默认值,请在第二个参数Html.Partial其执行到Html.Partial

@Html.Partial("searchHelp", Model.SomeStringProperty ?? "Enter Text")

You can assign a default value to the string-as-model from where it's called in the view: 您可以在视图中调用它的位置为字符串模型分配默认值:

//null coalesce to default string value:
@Html.Partial("searchHelp", Model.searchHelp ?? "default value")  

...though you might do better using an htmlhelper, where you can define the default value just one time: ...虽然您可以使用htmlhelper做得更好,您可以在其中定义默认值一次:

public IHtmlString SearchHelp(this HtmlHelper html, string searchHelp = "default value")
{
    // make html here
}

Then 然后

@Html.SearchHelp(Model.searchHelp);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM