我有一個稱爲等級的類,有5個不同的評級(1 =差...... 5 =優秀)。我也有一個模型(評論),它有10個問題,每個使用評級類。現在在視圖中,我在Review類中爲這些屬性中的每個屬性都設置了forEach,所以代碼在某種程度上被剪切掉了。而不是重複代碼,只是改變它們的屬性,我想要做的就是在Ratings類中創建一個方法,該類會生成剃刀語法,如果這是可能的話。在C#類中生成剃鬚刀語法併發送到查看
關於現在的樣子以及我想要做的事情如下。
當前視圖(只顯示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;
}
謝謝提前!
你嘗試使用部分意見? https://docs.asp.net/en/latest/mvc/views/partial.html – vittore
努力傳遞/讀取對象到Partial視圖並閱讀它。例如,如何傳遞和閱讀「model.ReviewModel.SpeakerReview」, – DanO
在簡單情況下,它將只是'@ Html.Partial(「SpeakerReviewPartial」,Model.ReviewModel.SpeakerReview)' – vittore