[英]How to set jQuery property from Model in ASP.NET MVC (razor)
我正在使用jQuery ratt插件為客戶評級。 我有以下jQuery代碼可用於創建老鼠對象:
$('.customerRating').raty({
path: '/Content/jQueryRaty/img/',
click: function (score, evt) {
var id = this.attr("ID");
$('input[name="' + id + '"]').val(score);
}
});
HTML結構如下(使用剃須刀):
@{
foreach (var customer in (IEnumerable<BL.Model.Customer>)ViewData["Customers"])
{
var id = "bRate_" + customer.ID;
@Html.Hidden(id);
<div id="leftcolumn"><span>@customer.Name</span></div>
<div id="rightcolumn"><span class="customerRating" id="@id"></span</div>
<br/>
}
}
這是創建新評分的解決方案。 我的問題是我該怎么做編輯評分的解決方案。 我的意思是我想將模型中的現有評級設置為html。
我當前的解決方案是:
@{
foreach (var item in Model.CustomerRating)
{
<text>
if (@item.RatingID >= 1)
{
$("#bRate_" + '@item.CustomerID' + "-1").attr("src", "/Content/jQueryRaty/img/star-on.png");
}
if (@item.RatingID >= 2)
{
$("#bRate_" + '@item.CustomerID' + "-2").attr("src", "/Content/jQueryRaty/img/star-on.png");
}
if (@item.RatingID >= 3)
{
$("#bRate_" + '@item.CustomerID' + "-3").attr("src", "/Content/jQueryRaty/img/star-on.png");
}
if (@item.RatingID >= 4)
{
$("#bRate_" + '@item.CustomerID' + "-4").attr("src", "/Content/jQueryRaty/img/star-on.png");
}
if (@item.RatingID >= 5)
{
$("#bRate_" + '@item.CustomerID' + "-5").attr("src", "/Content/jQueryRaty/img/star-on.png");
}
</text>
}
}
這很好用,但是在我看來,解決方案太傻了(例如,生成的JavaScript代碼過多冗余)。
為一個元素生成的jQuery批准代碼為:
<span id="bRate_123" class="customerRating">
<img title="bad" alt="1" src="/Content/jQueryRaty/img/star-on.png" id="bRate_123-1">
<img title="poor" alt="2" src="/Content/jQueryRaty/img/star-on.png" id="bRate_123-2">
<img title="regular" alt="3" src="/Content/jQueryRaty/img/star-on.png" id="bRate_123-3">
<img title="good" alt="4" src="/Content/jQueryRaty/img/star-on.png" id="bRate_123-4">
<img title="gorgeous" alt="5" src="/Content/jQueryRaty/img/star-off.png" id="bRate_123-5">
<input type="hidden" id="bRate_123-score" name="score" value="4">
</span>
jQuery raty具有start屬性,該屬性可以設置所選星星的默認數量。 看起來像:
$('.customerRating').raty({
start: @Model.RatingID
});
這樣,我可以從模型中設置默認的星數。 我可以針對具體ID進行此操作,但是如何為IEnumerable中的值設置此start屬性...
@foreach (var item in Model.CustomerRating)
?????? set start property .....
我希望這是可以理解的。 我將不勝感激,也可以通過其他任何提示或想法來解決此問題。
謝謝。
嗯,沒有太多的RAZOR瑣事,但您不能這樣做:
for (int i = 0; i < @item.RatingID; i++)
{
$("#bRate_" + '@item.CustomerID' + i).attr("src", "/Content/jQueryRaty/img/star-on.png");
}
但是直接從鼠聲中設置它當然更聰明,就像您說的:/
這行不行嗎?
@{
foreach (var item in Model.CustomerRating)
{
<text>
$('.customerRating').raty({ start: @Model.RatingID });
</text>
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.