与使用jQuery的Ajax加载PartialView? [英] Load PartialView with using jquery Ajax?
问题描述
PartialView
PartialView
@model OsosYeni23072012.Models.TblMeters
<h3>
Model.customer_name
</h3>
<h3>
Model.meter_name
</h3>
控制器
[HttpGet]
public ActionResult MeterInfoPartial(string meter_id)
{
int _meter_id = Int32.Parse(meter_id);
var _meter = entity.TblMeters.Where(x => x.sno == _meter_id).FirstOrDefault();
return PartialView("MeterInfoPartial", _meter);
}
剃须刀
@Html.DropDownList("sno", new SelectList(Model, "sno", "meter_name"), "-- Select Meter --", new { id = "meters"})
@Html.Partial("MeterInfoPartial")
我要加载的局部视图,如果DropDownList的变化。但我不知道我怎样才能做到这一点。我找不到这方面有任何的例子。我这样做与ActionLink的。但我没有用之前下拉列表。
I want to load partial view, if dropdownlist change. But I dont know How can I do this. I cant find any example about this. I do this with actionlink. But I did not with dropdown before.
控制器参数 meter_id
等于DropDownList的SelectedValue的。
controller parameter meter_id
equals dropdownlist selectedvalue.
感谢。
推荐答案
您可以订阅下拉的 .change()
事件,然后触发一个AJAX请求:
You could subscribe to the .change()
event of the dropdown and then trigger an AJAX request:
<script type="text/javascript">
$(function() {
$('#meters').change(function() {
var meterId = $(this).val();
if (meterId && meterId != '') {
$.ajax({
url: '@Url.Action("MeterInfoPartial")',
type: 'GET',
cache: false,
data: { meter_id: meterId }
}).done(function(result) {
$('#container').html(result);
});
}
});
});
</script>
和那么你就换部分具有给定一个id的div:
and then you would wrap the partial with a div given an id:
<div id="container">
@Html.Partial("MeterInfoPartial")
</div>
另外你为什么在你的控制器动作解析,离开这个给模型绑定:
Also why are you parsing in your controller action, leave this to the model binder:
[HttpGet]
public ActionResult MeterInfoPartial(int meter_id)
{
var meter = entity.TblMeters.FirstOrDefault(x => x.sno == meter_id);
return PartialView(meter);
}
要小心 FirstOrDefault
,因为如果它没有找到在给你的数据库匹配记录 meter_id
它将返回空
和你的部分,当您试图访问该模型将崩溃。
Be careful with FirstOrDefault
because if it doesn't find a matching record in your database given the meter_id
it will return null
and your partial will crash when you attempt to access the model.
这篇关于与使用jQuery的Ajax加载PartialView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!