MVC /剃刀/ JavaScript的新手问题:
我有一个MVC3 /剃刀形式,其中使用可以从下拉列表中选择的单品。
<div class="editor-label">
Product
</div>
<div class="editor-field">
@Html.DropDownList("ProductID", (IEnumerable<SelectListItem>)ViewBag.Products, "--Select One--")
@Html.ValidationMessageFor(model => model.ProductID)
</div>
那么,什么我要的是显示所选产品的价格只是下拉列表(型号属性名称是低于标签上的Amount
)。
这应该是很容易的,但我非常新的剃须刀,以及几乎一无所知的Javascript,所以我会很感激的是如何做到的任何详细解释,而这一切是如何挂在一起。
添加下拉下一个div /跨度。
@Html.DropDownList("ProductID", (IEnumerable<SelectListItem>)ViewBag.Products, "--Select One--")
<div id="itemPrice"></div>
在你的脚本,使到返回的价格您的控制器动作的一个Ajax调用。
$(function(){
$("#ProductId").change(function(){
var val=$(this).val();
$("#itemPrice").load("@Url.Action("GetPrice","Product")", { itemId : val });
});
});
而有这样一个控制器的动作在你的产品控制器
public string GetPrice(int itemId)
{
decimal itemPrice=0.0M;
//using the Id, get the price of the product from your data layer and set that to itemPrice variable.
return itemPrice.ToString();
}
这就对了 ! 请确保您有jQuery的在你的页面加载,这将很好地工作。
编辑:包括在你的页面加载jQuery库这一行(如果尚未加载)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
当用户选择一个产品的量不是提供给您的视图(记得在页面呈现在服务器上,但实际执行的客户端上;你的模型是无法在客户端的页面)。 所以,你要么必须包含在此基础上被传递到客户端的产品量的查找JavaScript数组中渲染(所以它通过客户端JavaScript的可用),或者你将不得不作出一个回调到服务器检索这些信息。
我会用jQuery来做到这一点。
这是一个什么样的jQuery的/ Javascript代码看起来就像如果你使用一个数组一个简单的例子。
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
// This code can easily be built up server side as a string, then
// embedded here using @Html.Raw(Model.NameOfPropertyWithString)
var list = new Array();
list[0] = "";
list[1] = "$1.00";
list[2] = "$1.25";
$("#ProductID").change(displayAmount).keypress(displayAmount);
function displayAmount() {
var amount = list[($(this).prop('selectedIndex'))];
$("#amount").html(amount);
}
});
</script>
<select id="ProductID" name="ProductID">
<option value="" selected>-- Select --</option>
<option value="1">First</option>
<option value="2">Second</option>
</select>
<div id="amount"></div>
你会想花一些时间看文档的jQuery的 。 最终你会用它颇有几分。 该代码基本上是“选择”下拉菜单中,重视处理程序的变化和按键事件。 当他们开火,它调用displayAmount功能。 displayAmount()检索所选索引,然后抓住值出名单的。 最后,它设置HTML到的金额。
取而代之的是本地数组的,你可以打电话给你的控制器。 您可以创建你的控制器返回的值作为JsonResult上的操作(方法)。 你会做一个使用回调jquery.ajax()。 在这里做一些搜索和jQuery的网站,我敢肯定你会发现吨关于如何做到这一点的例子。