作为 MVC 中的新功能,我试图通过 Ajax 调用将下拉列表值放入 mvc Controller ,这里是 View 代码:
<script type="text/javascript">
$(function () {
$('#myForm').submit(function () {
var select = $("#SeTime option:selected").val();
$.ajax({
url: this.action,
type: this.method,
data: {'selectedtTime' : select},
success: function(result) {
alert("Selected value: " + select);
}
});
return false;
});
});
</script>
<div >
@using (Html.BeginForm("Details", "Employee", FormMethod.Get, new { enctype = "multipart/form-data", id="myForm"}))
{
@Html.DropDownList("SeTime", new List<SelectListItem>
{
new SelectListItem{ Text="1 Min", Value = "60" },
new SelectListItem{ Text="2 Min", Value = "120" },
new SelectListItem{ Text="3 Min", Value = "180" },
}, "Select Time")
<input type="submit" value="Set Time " />
}
</div>
<p>@Model.SetTime</p> //to show the selected value thru controller to view
这是模型: 公开课时间 { 公共(public)字符串 SetTime { 获取;放; } }
这是 Controller :
public ActionResult Details(string selectedtTime)
{
Time time = new Time();
if (selectedtTime == null)
{
time.SetTime = "Hello";
}
else
{
time.SetTime = selectedtTime;
}
return View(time);
}
}
我在警报框中得到了正确的值,但在 Controller 中没有得到正确的值(每个选择都得到“Hello”)。我也尝试过 POST 方法,但没有成功。我可以得到一些如何通过 Controller 获取所选下拉值的建议
最佳答案
以下是具体操作方法。如果您需要更多信息,请告诉我。
查看:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index59</title>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
var userInterfaceGroups;//undefined at first
$("#btn").click(function (ev) {
var select = $("#SeTime option:selected").val();
alert(select);
$.ajax({
type: "POST",
url: "/Home/PostTime",
data: { 'selectedtTime': select },
dataType: "json",
success: function (response) {
},
error: function (Result) {
alert("Error");
}
});
})
})
</script>
</head>
<body>
@Html.DropDownList("SeTime", new List<SelectListItem>
{
new SelectListItem{ Text="1 Min", Value = "60" },
new SelectListItem{ Text="2 Min", Value = "120" },
new SelectListItem{ Text="3 Min", Value = "180" },
}, "Select Time")
@*ajax is a button click not a submit*@
<input type="button" value="Set Time" id="btn" />
</body>
</html>
Controller :
public class HomeController : Controller
{
[HttpPost]
public ActionResult PostTime(string selectedtTime )
{
//put a checkpoint here and interrogate selectedTime and work with it
return Json(new
{
aValue = "aValueRet"
}
, @"application/json");
}
关于jquery - 将下拉列表值获取到 mvc Controller 中以通过 Ajax 调用查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44661489/