ASP.NET MVC5图像上载程序在使用Ajax和jQuery发布表单时会产生问题



每次浏览按钮或图像上传器高亮显示时,单击创建按钮。我没有这个html元素的验证代码,也不明白为什么会发生这种情况。

我使用jQuery和Ajax发布此表单。
我使用ASP.NET MVC5
这是我的模型类

public partial class tbl_products
{
public int prod_id { get; set; }
[Required]
public string prod_name { get; set; }
public string prod_image_path { get; set; }
[NotMapped]
public HttpPostedFileBase ImageUpload { get; set; } // this is to upload images on project folder
public tbl_products()
{
prod_image_path = "~/Content/Images/choose_image.png";
}
}

这是我的控制器

public class ProductController : Controller
{
DemoDbEntities db = new DemoDbEntities();
// GET: Employee
public ActionResult Index()
{
return View();
}
public ActionResult ViewAllProducts()
{
return View(GetAllProducts());
}
IEnumerable<tbl_products> GetAllProducts()
{
return db.tbl_products.ToList<tbl_products>();
}
public ActionResult AddorEdit(int id = 0)
{
//create new object of prodocts to pass it to view
tbl_products prodObj = new tbl_products();//image path set to default image
return View(prodObj);
}
[HttpPost]
public ActionResult AddorEdit(tbl_products prodObj)
{
//check if the input type=file has image
if(prodObj.ImageUpload != null)
{
string fName = Path.GetFileNameWithoutExtension(prodObj.ImageUpload.FileName);
string fExten = Path.GetExtension(prodObj.ImageUpload.FileName);
fName = fName + DateTime.Now.ToString("yymmssfff") + fExten;
prodObj.prod_image_path= "~/Content/Images/" + fName;
//fName = Path.Combine(Server.MapPath("~/Content/Images/"), fName);
prodObj.ImageUpload.SaveAs(Path.Combine(Server.MapPath("~/Content/Images/"), fName));
}

db.tbl_products.Add(prodObj);
db.SaveChanges();
return RedirectToAction("ViewAllProducts");
}
}

下面是视图

@model WebApplicationDemo.tbl_products
@{
ViewBag.Title = "AddorEdit";
Layout = null;
}

@using (Html.BeginForm("AddorEdit", "Employee", FormMethod.Post,
new {enctype="multipart/form-data", onSubmit="return jQueryAjaxPost(this);"}))
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
@Html.HiddenFor(model => model.prod_id)
@*---------------------if no new image is selected then this old will be uploaded again-----*@
@Html.HiddenFor(model => model.prod_image_path)
@*@Html.ValidationSummary(true, "", new { @class = "text-danger" })*@

<div class="form-group">
@Html.LabelFor(model => model.prod_name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.prod_name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.prod_name, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.prod_image_path, new { @class = "control-label col-md-2"})
<div class="col-md-10">
<img src="@Url.Content(Model.prod_image_path)" style="margin:10px"
width="200" height="200" id="imagePreview" />
<input type="file" name="ImageUpload" accept="image/*" 
onchange="ShowImagePreview(this, document.getElementById('imagePreview'))" />
@*@Html.ValidationMessageFor(model => model.ImageUpload, "", 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>
}
<script src="~/Scripts/jquery-3.5.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Ajax和jQuery//使用Ajax将表单数据传递给控制器的方法函数jQueryAjaxPost(表单({

//$.validator.unobtrusive.parse(form);//to validate form validation
if ($(form).valid())
{
var ajaxConfig = { // this is a complete objecct
type: 'POST',
url: form.action,
data: new FormData(form),
success: function (response) {
$('#viewAllTab').html(response);
}
}
//check if the form has file uploader
//then set these two attributes to false
if ($(form).attr('enctype') == "multipart/form-data")
{
ajaxConfig["contentType"] = false;
ajaxConfig["processData"] = false;
}
$.ajax(ajaxConfig); // passing object to ajax function
}
else
{
return false;
}

}

我无法使用ajax post方法创建产品。

正如我在代码中看到的,在您的视图中,您使用@Html.AntiForgeryToken()

如果你想使用它,那么你也应该在你的控制器中使用它或者你把它从你的视图中删除:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddorEdit(tbl_products prodObj) {
//check if the input type=file has image
if (prodObj.ImageUpload != null) {
string fName = Path.GetFileNameWithoutExtension(prodObj.ImageUpload.FileName);
string fExten = Path.GetExtension(prodObj.ImageUpload.FileName);
fName = fName + DateTime.Now.ToString("yymmssfff") + fExten;
prodObj.prod_image_path = "~/Content/Images/" + fName;
//fName = Path.Combine(Server.MapPath("~/Content/Images/"), fName);
prodObj.ImageUpload.SaveAs(Path.Combine(Server.MapPath("~/Content/Images/"), fName));
}

db.tbl_products.Add(prodObj);
db.SaveChanges();
return RedirectToAction("ViewAllProducts");
}
}

当您提交表单时,您会将数据发送到Controller方法。若方法具有ValidateAntiForgeryToken属性,它将验证您发送的数据是否具有ForgeryTaken。

最新更新