当我在视图上选择一个选项时调用MVC控制器方法

本文关键字:选项 一个 调用 MVC 方法 控制器 视图 选择 | 更新日期: 2023-09-27 18:04:24

我有一个带有两个选项的选择标记。当一个选项被选中时,我想在控制器上调用一个方法。

控制器中的方法包含一个Switch,该Switch将根据所选选项设置3个单位。然后我想返回到初始视图,调用Action。

我有点难住了,一是如何触发视图中的动作,二是如何重定向到调用视图。

My View is below

@using <The controller name goes here>
@{
    ViewBag.Title = "Stuff";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Stuff</h2>
<p>More Stuff</p>
<label>Select a Room: </label>
<!-- I need to add Code that will loop through the database and provide rooms. 
        I will need to provide a query that will be called on page load.-->
<select id="roomList">
    <option value="1B^1001^01">1B^1001^01</option>
    <option value="1B^1002^01">1B^1002^01</option>
</select><br /><br />

Controller动作如下。

public Action getRoomNumber(string roomNumber, ref uint BVInstance, ref uint AVInstance, ref uint MVInstance)
        {
            switch(roomNumber)
            {
                case ("1B^1001^01"):
                    BVInstance = 3000018;
                    AVInstance = 3000022;
                    MvInstance = 3000040;
                    break;
                case("1B^1002^01"):
                    BVInstance = 3000020;
                    AVInstance = 3000023;
                    MvInstance = 3000042;
                    break;
                default:
                    break;
            }
            return Redirect()
        }

当我在视图上选择一个选项时调用MVC控制器方法

如果你使用Jquery,有一个简单的方法:

$("#roomList").change(function() {
    $(this).parents("form").submit();
});

但是你也需要更新你的html(在你的select周围添加一个表单):

<form action="controller/action">
  <select id="roomList">
    <option value="1B^1001^01">1B^1001^01</option>
    <option value="1B^1002^01">1B^1002^01</option>
  </select><br /><br />
</form>

在你的cs代码中,对于重定向,动作可以返回2个对象来处理你的重定向:

return RedirectToAction("action");

return View("viewName"); //Not quite sure about the parameters here, but you can read the doc ;-)

您需要在JavaScript中为<select>的更改事件设置一个事件处理程序。在该处理程序中,您将有一个对控制器的AJAX调用。

$("#roomList").on("change", function() {
        $.ajax({               {
              url: @Url.Action("getRoomNumber", "SomeController", new {roomNumber = $("#roomList :selected").text()}),
              context: document.body
        }).done(function() {
               // do whatever you need to do in your view here
               alert("Done!");
           });
});

我没有把这些引用变量传递给控制器,所以你需要这样做,以便你的控制器动作来改变它们

SELECT元素不能单独提交表单。当SELECT更改时,您需要使用某种形式的JavaScript来提交表单。

使用jQuery:

$("#roomList").on("change", function() {
    $(this).closest("form").submit();
});

则控制器动作可以返回视图的名称或重定向到显示视图的动作