【问题标题】:Most simple way to avoid code duplication in razor page避免剃刀页面中代码重复的最简单方法
【发布时间】:2020-07-05 08:58:22
【问题描述】:

asp dotnet core 2.1 避免代码重复的最简单方法是什么。我有一份问卷,例如问题类型编号,我有这样的代码。

<div class="form-group row">
<label class="control-label col-md-4 offset-md-0 pt-2">@question.Text:</label>
<div class="col-md-2" question-validation key="@question.Id">
    @{
        var key = question.Id.ToString();
        string value = null;
        if (Model.Answers.ContainsKey(key) && !string.IsNullOrWhiteSpace(Model.Answers[key]))
        {
            value = Model.Answers[question.Id.ToString()];
        }
    }
    <div class="form-group" >
        <input class="form-control" type="text" question-type="@QuestionType.Number" question-id="@question.Id" onkeypress="return isNumber(event)" value="@value">
    </div>
</div>

我想在单个页面上多次使用此代码,但我不想复制代码。

【问题讨论】:

  • 您可以使用 PartialView 或 ViewComponent。

标签: asp.net-core razor .net-core duplicates


【解决方案1】:

确定的方法是将该代码设置为PartialView,一旦成为局部视图,您就可以在任何地方调用它并将模型传递给它

<partial name="myPartialView" />
//Or with a model
@(await Html.PartialAsync("myPartialView", modelToPass))

【讨论】:

    猜你喜欢
    • 2021-04-10
    • 2021-11-12
    • 2019-09-04
    • 2020-05-18
    • 2021-11-29
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 2018-12-01
    相关资源
    最近更新 更多