Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC update partial view onchange drop down list

I want to update a partial view when user changes the current value of my drop down list.

With my onchange submit, the partial view does not load in div but replaces the whole page. How can I fix it?

view:

@using (Ajax.BeginForm("GetEnvironment", new RouteValueDictionary { { "Environment", Model.Environnements } }, new AjaxOptions() { UpdateTargetId = "ExportDiv" }))
{
    @Html.DropDownListForEnum(x => x.Environnements, new { onchange = "this.form.submit();" })
}

    <div id="ExportDiv">
        @Html.Partial("Export")
    </div>

Controller :

    public PartialViewResult GetEnvironment(ExampleDto model)
    {
        return PartialView("Export", model);
    }

Export.cshtml

like image 562
user3391714 Avatar asked Nov 30 '25 02:11

user3391714


1 Answers

It looks like triggering submit on the form causes whole page to be posted instead of AJAX behavior. Try this:

@using (Ajax.BeginForm("GetEnvironment", new RouteValueDictionary { { "Environment", Model.Environnements } }, new AjaxOptions() { UpdateTargetId = "ExportDiv" },new {id = "ajaxForm"))
{
    @Html.DropDownListForEnum(x => x.Environnements, new { onchange = "submitAjaxForm()" })
}

<div id="ExportDiv">
    @Html.Partial("Export")
</div>

<script type="text/javascript">
    $('form#ajaxForm').submit(function(event) { 
        eval($(this).attr('onsubmit')); return false; 
    });

    window.submitAjaxForm = function(){
        $('form#ajaxForm').submit();
    }
</script>

You need to include the scripts in thier own section if you are using it.

like image 97
Ufuk Hacıoğulları Avatar answered Dec 02 '25 15:12

Ufuk Hacıoğulları