简体   繁体   English

如何获取“的值”<select></select> ” 从视图到控制器的“ActionResult”?

[英]How to get the value of "<select></select>" from a view into a Controller's "ActionResult"?

I have a tag and a button.我有一个标签和一个按钮。 On click of the button, an actionResult in a controller is called.单击按钮时,将调用控制器中的 actionResult。 Like this.像这样。

<button type="button" onclick="location.href='@Url.Action("GetAllItems", "Items")'">Get Items</button>

And here's the ActionResult这是ActionResult

public ActionResult GetAllItems() {
        string selectedItem = string.Empty;
        ItemsRepository itemsRepository = new ItemsRepository();
        ModelState.Clear();
        return View(itemsRepository.GetAllItems());
    }

selectedItem is the variable I want to store either the selectedText or the selectedValue. selectedItem是我想要存储 selectedText 或 selectedValue 的变量。 But I don't know how to.但我不知道该怎么做。

This is the <Select> tag.这是<Select>标签。

<select style="width:170px" id="ItemsID" name="Items"></select>

And this is the rough function to get the different results from onChange event.这是从onChange事件获得不同结果的粗略函数。

<script>
$(document).ready(function () {
    $("#ItemsID").change(function () {
        var a = $('#ItemsID option:selected').val();
        var b = $('#ItemsID option:selected').text().trim();
        var c = $('#ItemsID option:selected').index();

        alert(a);
        alert(b);
        alert(c);
    })
});

Please help.请帮忙。

location.href doesn't sent a POST request. location.href 不发送 POST 请求。 What you got to do is to place a form tag with your ActionResult to make a POST request.你要做的是在你的 ActionResult 中放置一个表单标签来发出一个 POST 请求。

<form action='yourAction'>
<select name='name'></select>
<button type="submit">Get Items</button>
</form>

You can use following code to get the value of your select in the action method.您可以使用以下代码在操作方法中获取您选择的值。 Note that you must pass the name attribute of your html select element to Request.请注意,您必须将 html select 元素的name属性传递给 Request。

var selectedValue = Request["Items"];

Also, make sure the button that is clicked submits a form by using code like below.此外,请确保单击的按钮使用如下代码提交表单。

The main point is that you can only use Request object to access a html element value in C# code, provided the html element and the submit button are within the same form.要点是您只能使用 Request 对象来访问 C# 代码中的 html 元素值,前提是 html 元素和提交按钮在同一个表单中。 If you use a button that redirects the user rather than submits a form then this will not work, so it must be a submit type button as in code below.如果您使用重定向用户而不是提交表单的按钮,那么这将不起作用,因此它必须是提交类型按钮,如下面的代码所示。

@using (Html.BeginForm("YourActionName", "ControllerName")) {

          <select style="width:170px" id="ItemsID" name="Items"></select>

          <input type="submit" value="Submit Data" id="btnSubmit" />

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM