首页 > 解决方案 > 避免剃刀页面中代码重复的最简单方法

问题描述

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>

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

标签: asp.net-corerazor.net-coreduplicates

解决方案


The sure way is to make that code a PartialView once a partial view you can then call it anywhere and pass the model to it

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

推荐阅读