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. Both accept a parameter.
Now the Company view gets a parameter of type company and searchHelper accepts an optional string. 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.
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.
The @model
definition is not a value setter, it's merely telling Razor what type of view to instantiate. 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. Company
is not a string, obviously, so you get that error. If you want to pass a default value for the partial, do that in the second parameter to 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:
public IHtmlString SearchHelp(this HtmlHelper html, string searchHelp = "default value")
{
// make html here
}
Then
@Html.SearchHelp(Model.searchHelp);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.