c# – 模型在控制器中接收数据时是否保持其结构?

前端之家收集整理的这篇文章主要介绍了c# – 模型在控制器中接收数据时是否保持其结构?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我不确定我是否在主题上正确地提出了问题,但我会尽力向我解释我的问题.

我有以下ContactUsModel,它是Homeviewmodel的一部分,更好地说是单个模型中的嵌套模型类

public class ContactUsDataModel
{
   public string ContactName { get; set; }
   public string ContactEmail { get; set; }
   public string ContactMessage { get; set; }
   public string ContactPhone { get; set; }
}

我在Homeviewmodel中获取此模型,如下所示:

public class Homeviewmodel
{
   /*My other models goes here*/
   public ContactUsDataModel CUDModel { get; set; }
}

现在在Index.cshtml视图中,我强烈创建了一个表单视图,如下所示:

@model ProjectName.Models.Homeviewmodel
<!--I have other views for other models-->
@using (Html.BeginForm("ContactPost","Home",FormMethod.Post,new { id = "contactform" }))
{
    @Html.TextBoxFor(m => m.CUDModel.ContactName,new { @class="contact col-md-6 col-xs-12",placeholder="Your Name *" })
    @Html.TextBoxFor(m => m.CUDModel.ContactEmail,new { @class = "contact noMarr col-md-6 col-xs-12",placeholder = "E-mail address *" })
    @Html.TextBoxFor(m => m.CUDModel.ContactPhone,new { @class = "contact col-md-12 col-xs-12",placeholder = "Contact Number (optional)" })
    @Html.TextAreaFor(m=>m.CUDModel.ContactMessage,placeholder = "Message *" })
    <input type="submit" id="submit" class="contact submit" value="Send message">
 }

我做ajax Post如下:

$('#contactform').on('submit',function (e) {
   e.preventDefault();
   var formdata = new FormData($('.contact form').get(0));
   $.ajax({
            url: $("#contactform").attr('action'),type: 'POST',data: formdata,processData: false,contentType: false,//success
            success: function (result) {
                //Code here
            },error: function (xhr,responseText,status) {
                //Code here
            }
    });
});

在控制器中我试图接收如下:

public JsonResult ContactPost(ContactUsDataModel model)
{
     var name=model.ContactName; //null
     /*Fetch the data and save it and return Json*/
     //model is always null
}

由于某种原因,上述模型始终为null.但是,如果我将模型称为Homeviewmodel模型而不是如下所示的控制器参数中的ContactUsDataModel模型,则此方法有效:

public JsonResult ContactPost(Homeviewmodel model)
{
     var name=model.CUDModel.ContactName; //gets value
     /*Fetch the data and save it and return Json*/
     //Model is filled.
}

My question here is even though I fill model of type
ContactUsDataModel in the view I am getting it as null if I refer
directly,but ContactUsModel which is inside Homeviewmodel gets
filled. Doesn’t type of model matter here. Is the hierarchy its
referred is necessary while fetching in controller?

解决方法

好吧,如果你生成的< input> name是CUDModel.ContactName而不是简单的ContactName,默认的Model-Binder将无法绑定它.

幸运的是,您可以使用带有前缀的[Bind]属性

public JsonResult ContactPost([Bind(Prefix="CUDModel")]ContactUsDataModel model)
{
    // ...
}

MSDN

猜你在找的C#相关文章