【发布时间】:2023-03-28 18:31:01
【问题描述】:
作为 MVC 中的新功能,我正在尝试通过 Ajax 调用将下拉列表值导入 mvc 控制器,这里是 Views 代码:
<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
这是型号: 公开课时间 { 公共字符串 SetTime { 获取;放; } }
这里是控制器:
public ActionResult Details(string selectedtTime)
{
Time time = new Time();
if (selectedtTime == null)
{
time.SetTime = "Hello";
}
else
{
time.SetTime = selectedtTime;
}
return View(time);
}
}
我在警告框中得到了正确的值,但在控制器中却没有(每次选择都得到“你好”)。我也尝试过使用 POST 方法,但没有奏效。我可以得到一些建议如何通过控制器获取选定的下拉值
【问题讨论】:
-
我怀疑这是因为您将下拉列表和相应的 jQuery 拼写为
SeTime而不是SetTime。 -
您的代码看起来不错。它应该可以正常工作。你能看到网络选项卡并看到值是在查询字符串中传递的吗?
-
这是一个使用问题中的代码的工作 dot net fiddle :) dotnetfiddle.net/bh4Lid
-
@Zahir 如果您找到了解决方案,请告诉我?
-
@Zahir 你检查了我的答案stackoverflow.com/a/44663048/8175473 和最后一个.Netfiddle 链接的最后更新版本
标签: jquery ajax asp.net-mvc