[英]How to get the value of "<select></select>" from a view into a Controller's "ActionResult"?
我有一个标签和一个按钮。 单击按钮时,将调用控制器中的 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 的变量。 但我不知道该怎么做。
这是<Select>
标签。
<select style="width:170px" id="ItemsID" name="Items"></select>
这是从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);
})
});
请帮忙。
location.href 不发送 POST 请求。 你要做的是在你的 ActionResult 中放置一个表单标签来发出一个 POST 请求。
<form action='yourAction'>
<select name='name'></select>
<button type="submit">Get Items</button>
</form>
您可以使用以下代码在操作方法中获取您选择的值。 请注意,您必须将 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" />
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.