如何更新在MVC3 /剃刀回发一个标签 [英] How to update a label from a postback in MVC3/Razor
问题描述
MVC /剃刀/ JavaScript的新手问题:
MVC/Razor/Javascript newbie question:
我有一个MVC3 /剃刀形式,其中使用可从下拉列表中选择的单品。
I have a MVC3/Razor form where the use can select a single product from a drop down list.
<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>
那么,什么我要的是一个标签上只显示在下拉列表下方所选产品的价格(模型属性名称是金额
)。
这应该是pretty容易,但我在剃刀pretty新的,和几乎一无所知的Javascript,所以我会AP preciate的是如何做到的任何详细解释,以及它如何所有的挂在一起。
This should be pretty easy, but I am pretty new at Razor, and know almost nothing about Javascript, so I would appreciate any verbose explanations of how do do it, and how it all hangs together.
推荐答案
添加下拉下一个DIV / SPAN。
Add a div/span under the Dropdown .
@Html.DropDownList("ProductID", (IEnumerable<SelectListItem>)ViewBag.Products, "--Select One--")
<div id="itemPrice"></div>
和在你的脚本,使Ajax调用到控制器的一个动作,你回的价格。
and in your Script, make an ajax call to one of your controller action where you return the price.
$(function(){
$("#ProductId").change(function(){
var val=$(this).val();
$("#itemPrice").load("@Url.Action("GetPrice","Product")", { itemId : val });
});
});
和有这样一个控制器的动作在你的产品的控制器
and have a controller action like this in your Product controller
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在页面中,这将正常工作。
That is it ! Make sure you have jQuery loaded in your page and this will work fine.
编辑:包含这条线在你的页面加载jQuery库(如果尚未加载),
EDIT : Include this line in your page to load jQuery library ( If it is not already loaded),
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
这篇关于如何更新在MVC3 /剃刀回发一个标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!