让我们看看我们可以为您的案例做些什么:
将
id
分配给您的 select
以保存您将发送给服务器的值,并为 span
分配以显示服务器的输出:
<div class="form-group">
<label class="control-label">choice your Option</label>
<select id="ddlMaterial">
@foreach (var item in Materials)
{
<option value="@item.Id">
@item.MaterialName @item.Panel
</option>
}
</select>
<span class="main-price" id="priceDisplay">@item.Price</span>
</div>
现在我们定义将请求发送到服务器的
AJAX
调用。该请求将获取所选选项的当前 id
,然后将其转换为 JSON
字符串,发送到服务器进行处理。 url
是将在此调用中调用的操作方法:
$(document).ready(function () {
$("#ddlMaterial").change( function (event) {
var id = $(this).val();
var json = {id : id};
$.ajax({
type: 'POST',
url: "@Url.Action("GetPrice", "Home")",
dataType : "json",
data: {"json": JSON.stringify(json)},
success: function(data) {
if(data.status=="true")
{
$("#priceDisplay").text(data.price);
}
else
{
alert('Some error');
}
},
error: function(data) {
alert('Some error');
window.location.reload();
}
});
});
});
最后你的
Controller
操作方法将是:
using System.Web.Script.Serialization;
[HttpPost]
public JsonResult GetPrice(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
var id = Convert.ToInt32(jsondata["id"]);
//Get the price based on your id from DB or API call
var getMyPrice=GetPrice(id);
return Json(new {status="true", price= getMyPrice});
}