This question is not a repetition with this because all details are fully described in this question and will be very suitable for beginners
I have a view that inherits from a model. my field are in a form and I want to post form (or Model) to controller with JQuery/Ajax and insert it in database. I read this article and can upload image with ajax but i can not post whole form or model with data to controller.
my view :
@model ajax1.Models.Info
<form method="post" enctype="multipart/form-data">
<div class="form-group">
<label asp-for="FirstName" class="col-lg-2 col-sm-2 control-label "></label>
<div class="col-lg-6">
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName"></span>
</div>
</div>
<div class="form-group">
<label asp-for="LastName" class="col-lg-2 col-sm-2 control-label"></label>
<div class="col-lg-6">
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName"></span>
</div>
</div>
<input type="file" id="files" name="files" multiple />
<input type="button" id="upload" value="Upload Selected Files" />
</form>
JQuery Code at the bottom of view:
@section Scripts{
<script>
$("#upload").click(function (evt) {
var fileupload = $("#files").get(0);
var files = fileupload.files;
var data = new formdata();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
$.ajax({
type: "post",
url: "/home/uploadfilesajax",
contenttype: false,
processdata: false,
data: data,
success: function (message) {
alert(message);
},
error: function () {
alert("there was error uploading files!");
}
});
});
</script>
}
Controller :
[HttpPost]
public async Task<IActionResult> UploadFilesAjax(Info model)
{
var files = HttpContext.Request.Form.Files;
foreach (var Image in files)
{
if (Image != null && Image.Length > 0)
{
var file = Image;
var uploads = Path.Combine(_appEnvironment.WebRootPath, "img\\");
if (file.Length > 0)
{
var fileName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);
using (var fileStream = new FileStream(Path.Combine(uploads, fileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
model.imgName = fileName;
}
}
}
}
using (var db = _iServiceProvider.GetRequiredService<ApplicationDbContext>())
{
db.Info.Add(model);
db.SaveChanges();
}
string message = "success";
return Json(message);
}
Model :
public class Info
{
[DisplayName("First Name")]
[Required(ErrorMessage = "Enter First Name")]
public string FirstName { get; set; }
[DisplayName("Last Name")]
[Required(ErrorMessage = "Enter Last Name")]
public string LastName { get; set; }
[DisplayName("select image")]
public string imgName { get; set; }
}
When i put a breakpoint on the action and click on the submit button the application dose not go to action. How can i post all form or model to controller? I want if 'ModelStates.IsValid == false' the validation error shows.