Set the default value for the model passed to Partial View

I have a partial view that is called from another partial view (a view of nested partial views).

The external partial view is called Company, and the internal partial view is a custom control called searchHelp. Both take a parameter.

Now, a parameter of type company appears in the company view, and searchHelper accepts an optional string. This part works fine when I test the model value for null, and the default assignment is text as @((Model==null)?"Enter Text":Model)used in other views, without even passing a parameter.

In my case of nested views, if I do not provide the string as a model for searchHelper, then it takes companyas a model from the appearance of the company ie and gives an error.

+4
source share
2 answers

You can assign a default value to the model string from which it is called in the view:

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

... although you could better use htmlhelper, where you can only define the default value once:

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

Then

@Html.SearchHelp(Model.searchHelp);
0
source

@model , Razor, . . , , Company. Company , , . , Html.Partial:

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

Source: https://habr.com/ru/post/1533168/


All Articles