如何将整套模型附加到formdata并在MVC中获取 [英] How to append whole set of model to formdata and obtain it in MVC

查看:21
本文介绍了如何将整套模型附加到formdata并在MVC中获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过 formdata 传递一整套模型对象,并在控制器中将其转换为模型类型?

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

以下是我尝试过的!

JavaScript 部分:

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

然后通过 AJAX 传递它,它将是一个字符串,如果我检查 Request.Form["model"] 的值,结果将相同,即它将作为字符串和值将是 "[object object]"

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]"

有没有办法通过formdata传递模型并在控制器中接收它?

推荐答案

如果您的视图基于模型并且您已经在

标签内生成了控件,那么您可以序列化模型到 FormData 使用

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

这还将包括使用 <input type="file" name="myImage" .../>

并使用

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

并在您的控制器中

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

或(如果您的模型不包含 HttpPostedFileBase 的属性)

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

这篇关于如何将整套模型附加到formdata并在MVC中获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆