在C#类中生成剃刀语法并发送到视图

时间:2016-11-04 13:40:58

标签: c# asp.net-mvc razor

我有一个叫做评级的课程,有5个不同的评分(1 =差... 5 =优秀)。我还有一个模型(评论),它有10个问题,每个都使用评级类。现在在View中,我在Review类中为每个属性都有一个forEach,所以代码有点剪贴。我想做的不是复制代码而只是改变它们的属性,而是在Ratings类中创建一个生成剃刀语法的方法(如果可能的话)。

现在的示例以及我想做的事情如下。

当前视图(仅显示2个属性:

<tr>
    <td class="control-label col-md-4">
        @Html.LabelFor(model => model.ReviewModel.SpeakerReview, htmlAttributes: new { @class = "control-label " })
    </td>
    @foreach (var rating in ratingModel.RatingList)
    {
        <td class="col-md-1">
            @Html.RadioButtonFor(model => model.ReviewModel.SpeakerReview, rating.RatingId)
        </td>
    }
</tr>
<tr>
    <td class="control-label col-md-4">
        @Html.LabelFor(model => model.ReviewModel.AvHandoutsApplicable, htmlAttributes: new { @class = "control-label " })
    </td>
    @foreach (var rating in ratingModel.RatingList)
    {
        <td class="col-md-1">
            @Html.RadioButtonFor(model => model.ReviewModel.AvHandoutsApplicable, rating.RatingId)
        </td>
    }
</tr>

我希望它看起来如何:

查看:

<tr>
    <td class="control-label col-md-4">
        @Html.LabelFor(model => model.ReviewModel.SpeakerReview, htmlAttributes: new { @class = "control-label " })
    </td>
    @ReviewModel.BuildRatingList(ratingModel, ReviewModel.SpeakerReview);
</tr>
<tr>
    <td class="control-label col-md-4">
        @Html.LabelFor(model => model.ReviewModel.AvHandoutsApplicable, htmlAttributes: new { @class = "control-label " })
    </td>
    @ReviewModel.BuildRatingList(ratingModel, ReviewModel.AvHandoutsApplicable);
</tr>

类别:

public static string BuildRatingList(Rating ratingModel, object reviewItem)
{
    string RtnVal = "";
    foreach (var rating in ratingModel.RatingList)
    {
        RtnVal = "<td class='col-md-1'>@Html.RadioButtonFor(model => " + reviewItem + ", rating.RatingId)</td>";
    }
    return RtnVal;
}

提前致谢!

1 个答案:

答案 0 :(得分:1)

虽然您可以通过从NUGET插入额外的RazorEngine模块来完成您的要求,但我认为您最好使用普通partial viewsView Components,例如组件:

namespace ViewComponentSample.ViewComponents
{
    public class PriorityList : ViewComponent
    {
        private readonly ToDoContext db;

        public PriorityList(ToDoContext context)
        {
            db = context;
        }

        public async Task<IViewComponentResult> InvokeAsync(
        int maxPriority, bool isDone)
        {
            var items = await GetItemsAsync(maxPriority, isDone);
            return View(items);
        }
        private Task<List<TodoItem>> GetItemsAsync(int maxPriority, bool isDone)
        {
            return db.ToDo
                     .Where(x => x.IsDone == isDone && x.Priority <= maxPriority)
                     .ToListAsync();
        }
    }
}

并查看:

@using ViewComponentSample.Models
@using ViewComponentSample.ViewComponents
@model IEnumerable<TodoItem>

<h2>ToDo nameof</h2>

<div>
    @await Component.InvokeAsync(nameof(PriorityList), 
                      new { maxPriority = 4, isDone = true })
</div>