Load PartialView with using jquery Ajax?

江枫思渺然 提交于 2019-11-27 01:42:33

问题


PartialView

@model OsosYeni23072012.Models.TblMeters
<h3>
    Model.customer_name
</h3>
<h3>
    Model.meter_name
</h3>

Controller

[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);
}

Razor

@Html.DropDownList("sno", new SelectList(Model, "sno", "meter_name"), "-- Select Meter --", new { id = "meters"})

@Html.Partial("MeterInfoPartial")

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.

controller parameter meter_id equals dropdownlist selectedvalue.

Thanks.


回答1:


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>

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);
}

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.




回答2:


<script type="text/javascript">
    $(function() {
        $('#addnews').click(function() {
                $.ajax({
                    url: '@Url.Action("AddNews", "Manage")',
                    type: 'GET',
                    cache: false,
                }).done(function(result){
                    $('#containera').html(result);
                });
        });
    });
</script>


来源:https://stackoverflow.com/questions/11947540/load-partialview-with-using-jquery-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!