我是.net mvc的新手,我試圖創建一個請求並提交表單的簡單頁面。當我使用Ajax進行httppost請求時,頁面不會發布/重定向。Ajax在視圖中不起作用
JS文件這裏
<script>
$(document).ready(function() {
$("form").submit(function (e) {
var obj = {
Id : @Model.Id,
Name : '@Model.Name',
City : '@Model.City',
Gender : '@Model.Gender',
Dob : '@Model.Dob'
};
$.ajax({
url: '@Url.Action("Edit","Employee")',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(obj),
success: function (result) {
alert("Success");
},
failed: function (result) {
alert("Failed");
}
});
return false;
});
});
</script>
CSHTML鑑於此
[HttpPost]
public ActionResult Edit(Employee emp)
{
EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
if (ModelState.IsValid)
{
employeeBusinessLayer.Modify("Edit", emp);
return View();
}
else return RedirectToAction("Index");
}
當我點擊 '保存'
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Gender", new List<SelectListItem>
{
new SelectListItem { Text = "Male" , Value = "Male"},
new SelectListItem { Text = "Female" , Value = "Female"}
}, "Select Gender" , new { @class = "form-control"})
@Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Dob, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Dob, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Dob, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
控制器代碼,沒有任何反應!我在這裏錯過了什麼?
什麼是你想在這裏做什麼?發回剛剛發送給瀏覽器的原始模型值的要點是什麼?您在瀏覽器控制檯中遇到什麼錯誤? –
你有沒有檢查你的控制檯?對於任何錯誤? – Curiousdev
你也可以分享控制器代碼嗎?在控制端的郵政電話會發生什麼? –