Refactor similar CHTML that renders varying properties using EditorFor and LabelFor

前端 未结 2 1078
北荒
北荒 2020-12-04 02:57

I am building a project with a lot of common code regarding the razor view.

Example:

@Html.LabelFor(model =>
2条回答
  •  失恋的感觉
    2020-12-04 03:13

    Depends on what the types are for each of LayoutFrontAmount, LayoutFrontBackAmount, and LayoutTRC. Are these all strings? If so, you could have a common view file that stores the template for displaying each, and then display each of them by using @Html.Partial() in your primary view:

    MyView.cshtml

    @model string
    
    @Html.LabelFor(model => Model, htmlAttributes: new { @class = "control-label col-xs-12 col-sm-4 col-md-3" })
    @Html.EditorFor(model => Model, new { htmlAttributes = new { @class = "form-control" } })
    @Html.ValidationMessageFor(model => Model, "", new { @class = "text-danger" })

    And then in your main view file you could render each of LayoutFrontAmount, LayoutFrontBackAmount, and LayoutTRC as follows:

    @Html.Partial("MyView", Model.LayoutFrontAmount);
    @Html.Partial("MyView", Model.LayoutFrontBackAmount);
    @Html.Partial("MyView", Model.LayoutTRC);
    

    If they are different types, that poses a bigger challenge.

提交回复
热议问题