Monday, June 3, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
106
rated 0 times [  111] [ 5]  / answers: 1 / hits: 55194  / 9 Years ago, fri, march 27, 2015, 12:00:00

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?


More From » c#

 Answers
15

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');

[#67294] Wednesday, March 25, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brittanye

Total Points: 263
Total Questions: 94
Total Answers: 115

Location: Burkina Faso
Member since Thu, Dec 23, 2021
3 Years ago
brittanye questions
Mon, Aug 10, 20, 00:00, 4 Years ago
Tue, Jun 16, 20, 00:00, 4 Years ago
Wed, Apr 22, 20, 00:00, 4 Years ago
Mon, Apr 13, 20, 00:00, 4 Years ago
;