且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

与使用jQuery的Ajax加载PartialView?

更新时间:2023-12-05 11:32:52

您可以订阅下拉的 .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.