要从Ajax表单中提交ASP.NET MVC中的下拉列表,请遵循以下步骤:
public class MyModel
{
public int SelectedValue { get; set; }
public SelectList MySelectList { get; set; }
}
public ActionResult Index()
{
var model = new MyModel();
model.MySelectList = new SelectList(new[]
{
new SelectListItem { Value = "1", Text = "Option 1" },
new SelectListItem { Value = "2", Text = "Option 2" },
new SelectListItem { Value = "3", Text = "Option 3" },
}, "Value", "Text");
return View(model);
}
@model MyModel
@using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "POST", Url = "/Home/SubmitForm" }))
{
@Html.DropDownListFor(m => m.SelectedValue, Model.MySelectList, "Select an option", new { id = "myDropDown" })
<input type="submit" value="Submit" />
}
@section Scripts {
<script src="https://code.jquery.com/jquery.unobtrusive-ajax.min.js"></script>
}
[HttpPost]
public ActionResult SubmitForm(MyModel model)
{
// 处理表单提交逻辑
int selectedValue = model.SelectedValue;
// ...
// 返回结果
return Json(new { success = true, message = "Form submitted successfully" });
}
@section Scripts {
<script src="https://code.jquery.com/jquery.unobtrusive-ajax.min.js"></script>
<script>
$("form").on("submit", function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/Home/SubmitForm",
data: $(this).serialize(),
success: function (response) {
if (response.success) {
alert(response.message);
} else {
alert("An error occurred while submitting the form.");
}
},
error: function () {
alert("An error occurred while submitting the form.");
}
});
});
</script>
}
通过以上步骤,您可以从Ajax表单中提交ASP.NET MVC中的下拉列表。
领取专属 10元无门槛券
手把手带您无忧上云