Jquery Ajax调用不调用控制器操作方法来插入数据
我正在尝试将带有图像的数据插入数据库。数据存储到数据库中,一切正常,但当我尝试使用ajax做同样的事情时,ajax调用无法调用控制器操作方法。这是我的密码 这是我的表格Jquery Ajax调用不调用控制器操作方法来插入数据,jquery,ajax,asp.net-mvc,file-upload,Jquery,Ajax,Asp.net Mvc,File Upload,我正在尝试将带有图像的数据插入数据库。数据存储到数据库中,一切正常,但当我尝试使用ajax做同样的事情时,ajax调用无法调用控制器操作方法。这是我的密码 这是我的表格 <form id="InsertForm" name="InsertForm" enctype="multipart/form-data"> <div class="form-group"> <label for="Name">Name<
<form id="InsertForm" name="InsertForm" enctype="multipart/form-data">
<div class="form-group">
<label for="Name">Name</label>
<input type="text" class="form-control" name="StudentName" id="name"/>
</div>
<div class="form-group">
<label for="LastName">Last Name</label>
<input type="text" class="form-control" name="StudentLastName" id="last" />
</div>
<div class="form-group">
<label for="Address">Address</label>
<input type="text" class="form-control" name="StudentAddress" id="address"/>
</div>
<div class="form-group">
<label for="Gender">Gender</label>
<input type="text" class="form-control" name="Gender" id="gender"/>
</div>
<div class="form-group">
<label for="Image">Image</label>
<input type="file" class="form-control" id="StudentImage" name="StudentImage" />
</div>
<button id="saveclick" type="submit" name="save">Save</button>
</form>
您可以稍微修改一下jQueryAjax代码,然后再试一次吗
$.ajax({
url:@Url.Action("Insert", "Student", null),
Type:"POST",
data: new FormData( $( '#InsertForm' )[0] ),
success: function () {
alert("Data Saved Successfully");
},
error: function () {
alert("Please attach the Image");
}
});
为此:
JSON.stringify({'FormCollection':FormCollection})
,您不需要为FormCollection定义任何内容-FormCollection本质上隐式地拾取所有键/值对,因此您只需序列化表单或对象,如:$(“#formid”).serialize()请参阅如何使用ajax发布包含文件的模型(切勿使用FormCollection
-使用视图模型并绑定到视图模型)和使用return RedirectToAction(“显示”)在由ajax调用的方法中,code>是没有意义的(ajax调用从不重定向-其全部目的是保持在同一页面上)不起作用。我都试过了。我被卡住了:(诅咒它是有效的!(如果它对你不起作用,那么你没有正确地遵循代码)不起作用亲爱的,有其他解决方案吗?
[HttpPost]
public ActionResult Insert(FormCollection fm)
{
Student s = new Student();
s.StudentName = fm["StudentName"];
s.StudentLastName = fm["StudentLastName"];
s.StudentAddress = fm["StudentAddress"];
s.Gender = fm["Gender"];
HttpPostedFileBase file = Request.Files["StudentImage"];
file.SaveAs(HttpContext.Server.MapPath("~/Images/") + file.FileName);
s.StudentImage = file.FileName;
db.Students.Add(s);
db.SaveChanges();
return RedirectToAction("Show");
}
$.ajax({
url:@Url.Action("Insert", "Student", null),
Type:"POST",
data: new FormData( $( '#InsertForm' )[0] ),
success: function () {
alert("Data Saved Successfully");
},
error: function () {
alert("Please attach the Image");
}
});