How to append whole set of model to formdata and obtain it in MVC

Posted on

How to append whole set of model to formdata and obtain it in MVC – Even if we have a good project plan and a logical concept, we will spend the majority of our time correcting errors abaout javascript and c#. Furthermore, our application can run without obvious errors with JavaScript, we must use various ways to ensure that everything is operating properly. In general, there are two types of errors that you’ll encounter while doing something wrong in code: Syntax Errors and Logic Errors. To make bug fixing easier, every JavaScript error is captured with a full stack trace and the specific line of source code marked. To assist you in resolving the JavaScript error, look at the discuss below to fix problem about How to append whole set of model to formdata and obtain it in MVC.

Problem :

How do I pass a whole set model object through formdata and convert it to model type in the controller?

Below is what I’ve tried!

JavaScript part:

model = {
             EventFromDate: fromDate,
             EventToDate: toDate,
             ImageUrl: imgUrl,
             HotNewsDesc: $("#txthtDescription").val().trim(),
        };
formdata.append("model",model);

then pass it through AJAX, it will be a string, and if I check the value of Request.Form["model"] the result will be same, that is it will be received as string and value will be "[object object]"

Is there any way to pass model through formdata and receive it in the controller?

Solution :

If your view is based on a model and you have generated the controls inside <form> tags, then you can serialize the model to FormData using

var formdata = new FormData($('form').get(0));

This will also include any files generated with <input type="file" name="myImage" .../>

and post it back using

$.ajax({
  url: '@Url.Action("YourActionName", "YourControllerName")',
  type: 'POST',
  data: formdata,
  processData: false,
  contentType: false,         
});

and in your controller

[HttpPost]
public ActionResult YourActionName(YourModelType model)
{
}

or (if your model does not include a property for HttpPostedFileBase)

[HttpPost]
public ActionResult YourActionName(YourModelType model, HttpPostedFileBase myImage)
{
}

If you want to add additional information that is not in the form, then you can append it using

formdata.append('someProperty', 'SomeValue');

If you want to send Form data using Ajax.This is the way to send

var formData = new FormData();

//File Upload
   var totalFiles = document.getElementById("Iupload").files.length;


for (var i = 0; i < totalFiles; i++) {
    var file = document.getElementById("Iupload").files[i];

    formData.append("Document", file);
}

formData.append("NameCode", $('#SelecterID').val());
formData.append("AirLineCode", $('#SelecterID').val());


$.ajax({
        url: "/Controller/ActionName",
        type: "POST",
        dataType: "JSON",
        data: formData,
        contentType: false,
        processData: false,
        success: function (result) {
    }
})

Using Pure Javascript, considering you have

<form id="FileUploadForm">
   <input id="textInput" type="text" />
  <input id="fileInput" type="file" name="fileInput" multiple>
  <input type="submit" value="Upload file" />
</form>

JS

document.getElementById('FileUploadForm').onsubmit = function () {

var formdata = new FormData(); //FormData object

var fileInput = document.getElementById('fileInput');

//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
    //Appending each file to FormData object
    formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//text value
formdata.append("textvalue",document.getElementById("textInput").value);

//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/UploadFiles');
xhr.send(formdata); // se
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        //on success alert response
        alert(xhr.responseText);
    }
  }
  return false;
}  

in your C# controller you can get values it as below

[HttpPost]
public ActionResult UploadFiles(YourModelType model, HttpPostedFileBase fileInput)
{
      //save data in db
}

Reference : File Uploading using jQuery Ajax or Javascript in MVC

In view side ,if you are using ajax then,

$('#button_Id').on('click', function(){
        var Datas=JSON.stringify($('form').serialize());
        $.ajax({
            type: "POST",
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            url: '@Url.Action("ActionName","ControllerName")',
            data:Datas,
            cache: false,
            dataType: 'JSON',
            async: true,
            success: function (data) {

            },
        });
    });

In Controller side,

 [HttpPost]
 public ActionResult ActionName(ModelName modelObj)
 {
 //Some code here
 }

Leave a Reply

Your email address will not be published. Required fields are marked *