javascript 当在下拉列表中选择值时,MVC 使用 ajax 发布值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17148482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:15:55  来源:igfitidea点击:

MVC Post values using ajax when value selected in dropdownlist

javascriptajaxasp.net-mvcmodel-view-controllerasp.net-mvc-ajax

提问by Arne H. Bitubekk

I have several dropdownlists in a form. Each time the user selects a value in one of these dropdownlist do I want the value to be saved to the backend (database). I don't want to page to reload so I guess the best way to achive this is with ajax, and this is what I need help with.

我在一个表单中有几个下拉列表。每次用户在这些下拉列表之一中选择一个值时,我是否希望将该值保存到后端(数据库)。我不想重新加载页面,所以我想实现这一目标的最佳方法是使用 ajax,而这正是我需要帮助的。

How would I go about to get it to automaticly post the value to the server side when I select a value in a dropdownlist. Should I make 1 form for each of the drop down lists so I can update them individually? How do I get it to post the value as a ajax call, and not with a page reload? I'm using JQuery and JQuery mobile ontop of ASP MVC.

当我在下拉列表中选择一个值时,我将如何让它自动将值发布到服务器端。我应该为每个下拉列表制作 1 个表单,以便我可以单独更新它们吗?如何让它将值作为 ajax 调用发布,而不是重新加载页面?我在 ASP MVC 上使用 JQuery 和 JQuery mobile。

For demonstration purpose let me make show some code as it would be now: ViewModel:

出于演示目的,让我显示一些代码,就像现在一样:ViewModel:

public class ColorViewModel
{
    public ColorViewModel()
    {
        Options = new List<string>(){ "red", "blue", "green" };
    }

    public string Value { get; set; }

    public List<string> Options { get; set; }
}

View:

看法:

@model IEnumerable<ColorViewModel>

@using (Html.BeginForm())
{
    foreach(var item in Model)
    {
        Html.DropDownListFor(m => m.Value, Model.Options)
    }
    <input type="submit" value="Save">
}

I want to remove the submit button from the form and do all of the submiting of the form when the user selects a value (I guess this can be achived by using javascript)

我想从表单中删除提交按钮并在用户选择一个值时完成表单的所有提交(我想这可以通过使用 javascript 来实现)

采纳答案by Arne H. Bitubekk

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:

我最终没有发布表单,而是在更改时发布每个选择输入。我必须在发布的元素上使用“data-”属性附加我需要的所有值。例如,如果您想要附加一个 ID:

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

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

使用 jQuery 然后你可以这样做:

$(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.

它现在将发布到指定的 url。如果您有一个与您在数据中发布的对象具有相同属性名称的对象,它会自动将正确的值填充到这些对象中。

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.

另一个小笔记。如果您想采用其他方法发布整个表单(就像我首先做的那样),您必须隐藏提交按钮,然后使用 javascript 触发其单击事件以使用 ajax。只需使用javascript正常提交表单即可正常提交表单,而不是使用ajax。

回答by Samich

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

默认情况下,MVC 应id="Value"为该字段呈现(您可以在辅助方法的 HTML 参数中覆盖它)。

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

然后使用 jquery(如果您使用的是 MVC 项目模板,您应该已经在项目中拥有它)您可以发布您的表单:

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

回答by Rob Lyndon

Javascript is your best bet. Something like this:

Javascript 是您最好的选择。像这样的东西:

@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>