asp.net-mvc MVC 4 关于下拉列表更改的回发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19933115/
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-09-08 03:19:34  来源:igfitidea点击:

MVC 4 postback on Dropdownlist change

asp.net-mvcasp.net-mvc-4

提问by mmilan

I am using MVC4 and I have a menu inside of a layout. part of my menu consists of a dropdown list where a user can select between availiable providers.

我正在使用 MVC4,并且在布局中有一个菜单。我的菜单的一部分包含一个下拉列表,用户可以在其中选择可用的提供商。

<div class="row">
    <div class="col-md-4">
    @Html.DropDownListFor(x=> x.usr.DatUsrs.IdProvider, new SelectList(Lista, "Value","Text"))
    </div>
    <div class="col-md-3">
      Credit
      @Html.DisplayTextFor(x=> x.usrSelectedProvider.AvailiableCredit)
    </div>
    <div class="col-md-3">
      TEXT
    </div>
    <div class="col-md-2">
      Closing Day  @Html.DisplayTextFor(m=> m.usrSelectedProvider.ClosingDay)
    </div>
  </div>

the problem I am having is: when a user changes the selected item in the dropdownlist, I want to make a postback to be able to load the AvailiableCredit and ClosingDay. In webforms i could do this with autopostback, but I haven't found a way to do this in MVC4

我遇到的问题是:当用户更改下拉列表中的选定项目时,我想进行回发以便能够加载 AvailiableCredit 和 ClosingDay。在 webforms 中,我可以使用 autopostback 来做到这一点,但我还没有找到在 MVC4 中做到这一点的方法

回答by David

There are a couple of ways to do this, but first you need to understand the structure of what you're doing.

有几种方法可以做到这一点,但首先你需要了解你正在做的事情的结构。

It's not a "post back" in MVC (or, really, in HTTP in general... WebForms lied to you). What you're trying to do is simply post data to the server and receive a response. In the MVC Framework, the target of that post would be a controller action. The response can be a couple of different things, depending on the approach you take.

它不是 MVC 中的“回发”(或者,实际上,一般来说,在 HTTP 中……WebForms 对您撒了谎)。您要做的只是将数据发布到服务器并接收响应。在 MVC 框架中,该帖子的目标是控制器操作。根据您采用的方法,响应可以是几种不同的东西。

I recommend writing some JavaScript to perform this task via AJAX. That way the page doesn't refresh and you're only sending/receiving the data relevant to the specific task at hand. ASP.NET MVC comes with jQuery, so I'm going to assume the use of jQuery in this case.

我建议编写一些 JavaScript 来通过 AJAX 执行此任务。这样页面就不会刷新,您只会发送/接收与手头特定任务相关的数据。ASP.NET MVC 带有 jQ​​uery,因此在这种情况下我将假设使用 jQuery。

First you'd need to bind to the change event for that selectelement. It's probablyidentified with the id"IdProvider" but you'll want to check the rendered HTML to make sure. Assuming it is, you can use something like this:

首先,您需要绑定到该select元素的更改事件。它可能id“IdProvider”标识,但您需要检查呈现的 HTML 以确保。假设是这样,你可以使用这样的东西:

$('#IdProvider').change(function () {
    // respond to the change event in here
});

Now you can make the AJAX call to the server within that handler. It might be something as simple as:

现在您可以在该处理程序中对服务器进行 AJAX 调用。它可能很简单:

var selectedValue = $('#IdProvider').val();
$.post('@Url.Action("MyAction", "MyController")', { selection : selectedValue }, function (data) {
    // handle the server response here
});

With this, the controller action would have the selected value available in an argument called selection:

这样,控制器操作将在名为 的参数中具有可用的选定值selection

public ActionResult MyAction(string selection)
{
    // do your server-side processing and get your data
    return Json(data);
}

This action returns Json formatted data, since it's being used by JavaScript on the client. So when handling the response in the $.post()call above, you'd get that data in the datavalue there.

此操作返回 Json 格式的数据,因为客户端上的 JavaScript 正在使用它。因此,在处理上述$.post()调用中的响应时,您会在data那里的值中获得该数据。

What you do with that data in the JavaScript code is then up to you. If it's a simple structure with the two values you're looking for, it might be something as simple as this:

你在 JavaScript 代码中如何处理这些数据取决于你。如果它是一个具有您正在寻找的两个值的简单结构,它可能是这样简单的:

$('#AvailableCredit').text(data.AvailableCredit);
$('#ClosingDay').text(data.ClosingDay);

Alternatively, you couldwrap the selectelement in a formand post the whole thing when the selection changes, and the controller action would then want to return a Viewwith the data populated in that view. But that's likely overkill since all you want to do is send one value and receive two values.

或者,您可以select元素包装在 a 中form并在选择更改时发布整个内容,然后控制器操作将希望返回 aView并在该视图中填充数据。但这可能有点矫枉过正,因为您要做的只是发送一个值并接收两个值。

回答by Abhijeet Nagre

Disclaimer: This approach will submit entire form. If possible, it is better to perform an Ajax operation instead of form submit. Answer by David explains how to do Ajax call.

免责声明此方法将提交整个表格。如果可能,最好执行 Ajax 操作而不是表单提交。David 的回答解释了如何进行 Ajax 调用。

If one adds class data-on-change-submitto the select list (or any input element, which should trigger post back). Then it is possible to add event handler; which will submit form on change, as follows.

如果将类data-on-change-submit 添加到选择列表(或任何应该触发回发的输入元素)。然后可以添加事件处理程序;这将提交更改表单,如下所示。

$(function () {
    $(".data-on-change-submit")
        .change(function ()
                {
                   var form = button.closest("form");
                   form.submit();
                })
});

回答by Oualid KTATA

In MVC there is no need for a post back, When the user selects from the dropdown, redirecect to the same action again but this time the action will have a HttpPost attribute (that will be your postback). Then you can do whatever you like and re-render the same view but this time with a new view model (having your new data loaded: AvailiableCredit and ClosingDay)

在 MVC 中不需要回发,当用户从下拉列表中选择时,再次重定向到相同的操作,但这次操作将具有 HttpPost 属性(这将是您的回发)。然后你可以做任何你喜欢的事情并重新渲染相同的视图,但这次使用新的视图模型(加载新数据:AvailableCredit 和 ClosingDay)

    public ActionResult DisplayMainView()
    {    
      LoadDataOnDropDown();    
      return View();    
    }

on the dropdown when a user selects the value, redirect to action (with httpPost) and give whatever value you need to reload the data.

在用户选择值时的下拉列表中,重定向到操作(使用 httpPost)并提供重新加载数据所需的任何值。

[HttpPost]
public ActionResult DisplayMainView(string selectedValueFromDropdown) {

// get AvailiableCredit and ClosingDay  based on selection
ViewBag.AvailiableCredit = myService.GetAvailiableCredit (selectedValueFromDropdown);
ViewBag.ClosingDay   = myService.GetClosingDay (selectedValueFromDropdown);

return View;

}

This a pseudo-code that illustrate how you should use HttpPost to simulate the webForm postback. N.B.:I Used the viewbag but I would suggest using a seperate viewmodel for every view you create.

这是一个伪代码,说明您应该如何使用 HttpPost 来模拟 webForm 回发。注意:我使用了 viewbag,但我建议为您创建的每个视图使用单独的视图模型。