如何将结果从HTMLDropDownList传递给MVC控制器?

时间:2015-07-24 12:39:33

标签: c# jquery asp.net asp.net-mvc asp.net-mvc-5

我有一个HTML.DropDownList的视图。我想弄清楚如何捕捉选择。选择包含两个值,只能选择一个值。该值是一个房间号,它将是控制器中我的Switch的字符串输入。

我已经让下拉列表正常工作,我已经让模型工作并将数据发送到视图。我无法弄清楚如何传递DropDownList的值。

我知道我需要一些Jquery来触发控制器的POST,但不知道要写什么。任何帮助表示赞赏。代码如下。

@using (Html.BeginForm("SelectRoomNumber", "PEO"))
{
    <fieldset>
        Room Numbers
        @Html.DropDownList("RoomList", (SelectList) ViewBag.RoomList)
        <p>
            <input type="submit" value="Submit" />
        </p>

    </fieldset>

我在PEO控制器中调用方法SelectRoomNumber。

[HttpPost]
        public ActionResult SelectRoomNumber()
        {

            string roomNumber ="";
            string readValueBv = "T";
            string readValueAv = "80";
            string readValueMv = "Occ";

            switch (roomNumber)
            {
                case ("1B^1001^01"):
                    model.RmNum = "1B^1001^01";
                    model.BvInstance = 3000018;
                    model.AvInstance = 3000022;
                    model.MvInstance = 3000040;
                    break;

                case ("1B^1002^01"):
                    model.RmNum = "1B^1002^01";
                    model.BvInstance = 3000020;
                    model.AvInstance = 3000023;
                    model.MvInstance = 3000042;
                    break;

                default:
                    model.RmNum = "Room";
                    model.BvInstance = 0;
                    model.AvInstance= 0;
                    model.MvInstance= 0;
                    break;
            }

            //Start BACnet Message Que
            _bacnetAgent.StartActivity(IpAddress);
            Thread.Sleep(2000);

            //Trigger Read Method BV
            _bacnetAgent.Read(deviceId, BvReadBacObj, model.BvInstance, BacProp, out readValueBv);
            model.BvRes = readValueBv;

            //Trigger Read Method AV
            _bacnetAgent.Read(deviceId, AvReadBacObj, model.AvInstance, BacProp, out readValueAv);
            model.AvRes = readValueAv;

            //Trigger Read Method MV
            _bacnetAgent.Read(deviceId, MvReadBacObj, model.MvInstance, BacProp, out readValueMv);
            model.MvRes = readValueMv;

            return View("PEO", model);

        }

3 个答案:

答案 0 :(得分:1)

只需创建一个与select元素的属性名称相同的变量。

[HttpPost]
public ActionResult SelectRoomNumber(string RoomList)
{
//rest of your code

}

答案 1 :(得分:1)

如果你想把它作为整数,只需添加它:

[HttpPost]
public ActionResult SelectRoomNumber(int RoomList)
{

}

否则作为字符串:

[HttpPost]
public ActionResult SelectRoomNumber(string RoomList)
{

}

RoomList是您在视图中输入的关键名:

@Html.DropdownList("KEYNAME")

答案 2 :(得分:0)

MVC视图与关联控制器密切配合,因此只要视图和控制器中的id为<,您就可以将一个或多个值从视图传递给控制器强>同名。例如 在你的控制器中你有这个

[HttpPost]
public ActionResult SelectRoomNumber(string RoomList)
{
}

在你看来你应该有这个

Html.Textbox("RoomList")