【问题标题】:How to get the value of "<select></select>" from a view into a Controller's "ActionResult"?如何从视图中获取“<select></select>”的值到控制器的“ActionResult”中?
【发布时间】:2019-01-21 04:02:22
【问题描述】:

我有一个标签和一个按钮。单击按钮时,将调用控制器中的 actionResult。像这样。

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

这是ActionResult

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

selectedItem 是我要存储 selectedText 或 selectedValue 的变量。但我不知道该怎么做。

这是&lt;Select&gt; 标签。

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

这是 rough 函数,用于从 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);
    })
});

请帮忙。

【问题讨论】:

  • 您可以使用 AJAX 绑定 change 事件将选定的值传递给控制器​​操作方法的参数。您是否已经了解如何使用 AJAX 调用?
  • 我不希望它绑定在onChange 事件上,我想在onClick 按钮事件上得到它。

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


【解决方案1】:

location.href 没有发送 POST 请求。你要做的是在你的 ActionResult 中放置一个表单标签来发出一个 POST 请求。

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

【讨论】:

  • 这是ActionResult吗? View 对我来说看起来像 HTML。
  • @using (Html.BeginForm("GetAllItems", "Items", FormMethod.Post, new { id = "thisForm"})) { }
  • 感谢您的帮助。
【解决方案2】:

您可以使用以下代码在 action 方法中获取您选择的值。请注意,您必须将 html select 元素的 name 属性传递给 Request。

var selectedValue = Request["Items"];

此外,请确保单击的按钮使用如下代码提交表单。

主要的一点是,你只能使用 Request 对象来访问 C# 代码中的 html 元素值,前提是 html 元素和提交按钮在同一个表单中。如果您使用重定向用户而不是提交表单的按钮,那么这将不起作用,因此它必须是提交类型的按钮,如下面的代码所示。

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

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

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

}

【讨论】:

  • 返回如下错误selectedValue Cannot obtain value of the local variable or argument because it is not available at this instruction pointer, possibly because it has been optimized away.
  • 我已经取消选中Optimize Code检查,让我再试一次。
  • 选择元素是包含项目还是为空?
  • 它不是空的。它被另一个 ActionResult 填充。
  • 这是填充&lt;select&gt;标签public ActionResult ItemList() { var items = Items.GetItems(); if (HttpContext.Request.IsAjaxRequest()) { return Json(new SelectList(items.ToArray(), "ItemCode", "ItemDescription"), JsonRequestBehavior.AllowGet); } return RedirectToAction("Index"); }的代码
猜你喜欢
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多