[英]Pass drop-down list values from view to controller
I have a select tag with several options and each of the options are designated a value. 我有一个带几个选项的select标记,每个选项都指定了一个值。
<select id="dropdown">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
Additionally, I have the following JQuery script. 另外,我有以下JQuery脚本。
$(function() {
$(#dropdown).change(function() {
var option = $(this).find("option:selected").text();
var optionValue = $(this).val();
I've checked both values using an 'alert' and they're correct. 我已经使用“警报”检查了两个值,它们是正确的。 Now I want to pass these values from the view to the controller.
现在,我想将这些值从视图传递到控制器。 I put the select tag within a form and tried using '.submit()' on both values, but that causes the script to crash.
我将select标记放在表单中,并尝试在两个值上使用'.submit()',但这会导致脚本崩溃。 I'm not sure if I'm using '.submit()' correctly, as I'm a beginner in JavaScript and Jquery.
我不确定我是否正确使用'.submit()',因为我是JavaScript和Jquery的初学者。 So in short, how can I get the option tag value into a method of my controller?
简而言之,如何将选项标签值添加到控制器的方法中?
EDIT 1 编辑1
The select tags are in a form, and I've been trying to submit like this: select标签采用表格形式,我一直在尝试像这样提交:
$(this).val().submit()
EDIT 2 编辑2
Additionally, here is the controller method I'm trying to get the value into. 此外,这是我尝试获取值的控制器方法。
[HttpPost]
public ActionResult Index(string dropdown)
{
string value = dropdown;
//--- conditional logic ---
return View()
}
To use submit()
your dropdown must be in a <form>
要使用
submit()
您的下拉列表必须位于<form>
<form method="POST" action="yourControllerUrl/MyAction">
<select id="dropdown" name="dropdownName">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
</form>
And in the controller : 并在控制器中:
public ActionResult MyAction(string dropdownName)
{
// use your dropdown value here
}
You can use ajax to do this kind of task 您可以使用ajax来完成此类任务
var dropDownVal = $("#dropdown").val();
$(#dropdown).change(function() {
$.ajax({
url : yourControllerUrl/MyAction,
type: "POST",
data : {
dropDown : dropDownVal
}
});
});
In controller use params and get the value with "dropDown" as key 在控制器中使用params并使用“ dropDown”作为键来获取值
Best way would be to expand on this.... :) hope it helps. 最好的方法是在此基础上扩展.... :)希望能有所帮助。
Model 模型
public class Model
{
public int Id { get; set; }
public IEnumerable<Items> items { get; set; }
}
View 视图
@model App.Models.Model
@using (Html.BeginForm("ActionName", "ControllerName")) {
@Html.DropDownListFor(x => x.Id, Model.Items)
<button type="submit" class="btn btn-info"><i class="fa fa-floppy-o"></i></button>
}
Controller 控制者
public ActionResult ActionName(Model model)
{
var blah = model.items;
return View(model);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.