MVC Post values using ajax when value selected in dropdownlist

南笙酒味 提交于 2019-12-06 02:01:28

By default MVC should render id="Value" for this field (you can override it in HTML params of helper method).

Then using jquery (if you are using MVC project template you already should have it in the project) you can post your form:

$(function() {
    $('#Value').change(function() {
        this.form.submit();
    });
});

Javascript is your best bet. Something like this:

@using (Html.BeginForm("", "", FormMethod.Post, new { id = "myForm" }))
{
    foreach(var item in Model)
    {
        Html.DropDownListFor(m => m.Value, Model.Options, new { id = "myList" })
    }
}

<script type="text/javascript">
    $(document).ready(function() {
        $("#myList").change(function() {
            $("#myForm").submit();
        });
    });
</script>

I ended up not posting the form but posting each of the select inputs when they change. I had to attach all the values I needed using "data-" attribute on the element posted. For example if you want a ID attached to it:

@Html.DropDownListFor(m => m.Value, Model.Options, new { @data_Id = Model.Id, })

Using jQuery then you're able to do it this way:

$(function() {
    $('.dropdown').change(function() {
        $.ajax(
            {
                type: "POST",
                url: "Controller/Action",
                data: {
                    Value: $(this).val(),
                    Id: $(this).attr('data-Id'),
                }
            });
    });
});

It will now be posted to the url spesified. If you have a object with the same property name as the one you're posting in the data will it automaticly fill the correct values into these.

Another small note. If you want to go for the other approach with posting the whole form (as I did first) must you hide the submit button then trigger its click event with javascript for it to use ajax. Just submiting the form normally with javascript will the form be submitted normally and not using ajax.

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