【问题标题】:MVC posting Null value to POST method of ControllerMVC 将 Null 值发布到 Controller 的 POST 方法
【发布时间】:2013-02-08 06:01:11
【问题描述】:

我正在使用 ViewModel 类来绑定数据输入页面, 视图模型类的层次结构是这样的

public ClassA
{
    public SomeModelType1 MyProperty1 { get; set; }
    public List<SomeModelType2> MyProperty2 { get; set; }
}

public class SomeModelType1 
{
    public string Name { get; set; }
    public SomeModelType3 MyProperty13 { get; set; }
}
public class SomeModelType3
{
    public int Id { get; set; }
}

当我将 A 类绑定到视图时,我将文本框绑定如下:

模型.MyProperty1.Name)%> 和 Model.MyProperty1.SomeModelType3 .Id,新 { @id = "hdfId" })%>

但是当我提交我写的表格时, [AcceptVerbs(HttpVerbs.Post)] 公共 ActionResult BuildProfile(ClassA a) { //一些逻辑 }

所以当我调试 a.MyProperty1 值时,我总是将 MyProperty1 设为空值,能否请一些人帮忙? 我不明白我哪里出错了。


获取方法

 [AcceptVerbs(HttpVerbs.Get)]
public ActionResult BuildProfile(Int32 UserId, Int32 CompanyDentistId, Int32 AccountId)
{
A objProfile = new A ();          
objProfile.CurrentStep = 1;
objProfile.MyProperty1.MyProperty13.CompanyId = CompanyId;
objProfile.MyProperty1.MyProperty13.AccountId = AccountId;
objProfile.MyProperty1.UserId = UserId;
return View(objProfile);
}

发布方法

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult BuildProfile(BuildProfileViewModel a)
    {          
        return RedirectToAction("BuildProfile", new { UserId = a.MyProperty1.UserId, CompanyId = a.MyProperty1.MyProperty13.CompanyId, AccountId = a.MyProperty1.MyProperty13.AccountId });

}

查看

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/DefaultMaster.Master"
Inherits="System.Web.Mvc.ViewPage<ChooseYourDentist.ViewModel.BuildProfileViewModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>"
    type="text/javascript"></script>
<script type="text/javascript">
    var stepCounter = 1;
    var TotalSteps = 4;
    function IntializeLoader() {

        $("#divAJAXLoader").dialog({
            autoOpen: false,
            height: 50,
            width: 100,
            modal: true,
            resizable: false,
            draggable: false
            //position: ["center", "center"],
            // , autoOpen: false
        });
        $(".ui-dialog-titlebar").hide();
    }
    function OnSuccess(data) {
        if (data.result == 1) {
            var UserId = data.userid;
            // window.location.href = '/Dentist/ViewCompanyProfile?UserID=' + UserId + '';
        }
        else {
            alert("Some error occured while trying to save the data, Please try again.");
        }
    }
    function OnBegin() {
        $("#divAJAXLoader").dialog("open");
        return CompareDates($("#FromDate").val(), $("#ToDate").val());
    }
    function OnComplete() {
        $("#divAJAXLoader").dialog("close");
    }
</script>

<% using (Html.BeginForm("BuildProfile", "Dentist", Model, FormMethod.Post, new { dmodel = Model, @id = "frmBuildProfile" }))
   {
       ChooseYourDentist.Models.UserAccountModel obj1 = new ChooseYourDentist.Models.UserAccountModel();
       this.Model.MyProperty1 = obj1;
       %>
<div>
    <h5>
        Add/Edit<span> Doctor Profile</span></h5>
    <div class="req_an_process">
        <div class="build_p_block">
            <div class="progress_bar">
                <div class="req_selected">
                    Basic Profile
                </div>
                <div class="req_deselected">
                    Dentist Profile
                </div>
                <div class="req_deselected_last">
                    Gallery
                </div>
                <div class="clear">
                </div>
            </div>
            <div class="form_content" id="First">
                <h4>
                    Basic Profile</h4>
                <p>
                    ChooseYourDentist.com makes it easy for dentists and patients to connect. Simply
                    complete the information below and you'll be on your way to connecting with more
                    patients.</p>
                <ul>
                    <li>First Name:</li>
                    <li class="mar_bot">
                        <%: Html.TextBoxFor(model => model.MyProperty1.FirstName)%>
                        <%: Html.ValidationMessageFor(model => model.MyProperty1.FirstName)%></li>
                    <li>Last Name:</li>
                    <li class="mar_bot">
                        <%: Html.TextBoxFor(m=> Model.MyProperty1.LastName)%>
                        <%: Html.ValidationMessageFor(m=> Model.MyProperty1.LastName)%></li>
                    <li>Gender:</li>
                    <li class="mar_bot">
                        <%: Html.RadioButtonFor(model=>Model.MyProperty1.MyProperty13.Gender,"Male", new { id = "rbtnMale" }) %>Male
                        <%: Html.RadioButtonFor(model=>Model.MyProperty1.MyProperty13.Gender,"Female", new { id = "rbtnFemale" }) %>Female
                    </li>
                    <li>Title:</li>
                    <li class="mar_bot">
                        <%= Html.DropDownListFor(m=> Model.MyProperty1.MyProperty13.TitleId, new SelectList((IEnumerable)ViewData["lstTitle"], "ReferenceDataId", "ReferenceDataName"), "-Select Title-", new { @id = "ddlTitle" })%>
                    </li>

                    <li class="mar_bot">
                        <input type="submit" class="green_btn" value="Save" name="Save" />

                    </li>
                </ul>
            </div>
            <div class="form_content" id="second" style="display: none;">
                <h4>
                    Dentist Profile</h4>
            </div>
        </div>
    </div>
</div>
<%=Html.HiddenFor(m=> Model.CurrentStep, new { @id = "hdfCurrentStep" })%>
<%=Html.HiddenFor(m=> Model.TotalSteps, new { @id = "hdfTotalSteps" })%>
<%=Html.HiddenFor(m=> Model.MyProperty1.UserId, new { @id = "hdfUserId" })%>
<%=Html.HiddenFor(m=> Model.MyProperty1.MyProperty13.CompanyId, new { @id = "hdfCompanyId" })%>
<%=Html.HiddenFor(m=> Model.MyProperty1.MyProperty13.AccountId, new { @id = "hdfAccountId" })%>
<% } %>
<div id="divAJAXLoader" style="display: none; text-align: center;">
    <img src="<%: Url.Content("~/Content/images/indicator_white.gif") %>" alt="Loading..." />
</div>

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    据我所知,MVC模型中的继承范围仅限于2个或更少的继承,不能滥用

    public ClassA
    {
    
    
    //properties of SomeModelType1
    public string Name { get; set; }
    //propperties of SomeModelType3
    public int Id { get; set; }
    //if you need a list of int
    //public list<int> Id   
    
    
    //missing SomeModelType2
    public List<SomeModelType2> MyProperty2 { get; set; }   
    }
    

    【讨论】:

      【解决方案2】:

      在您绑定回来的所有视图中,视图使用的每个类都需要一个无参数构造函数。您还需要在该构造函数的视图中实例化您在视图中使用的每个类。

      public ClassA
      {
          public ClassA(){
              MyProperty1 = new SomeModelType1();
              MyProperty2 = new List<SomeModelType2>();
          }
      
          public SomeModelType1 MyProperty1 { get; set; }
          public List<SomeModelType2> MyProperty2 { get; set; }
      }
      
      public class SomeModelType1 
      {
          public SomeModelType1(){
              MyProperty13 = new SomeModelType3();
          } 
      
          public string Name { get; set; }
          public SomeModelType3 MyProperty13 { get; set; }
      }
      public class SomeModelType3
      {
          public int Id { get; set; }
      }
      

      【讨论】:

      • 嗨,我按照你的方法试过了,但我在回发时仍然得到 Null 值
      • 嗨,我查看了模型状态,它给了我以下错误“从类型 'System.String' 到类型 'SomeModelType1' 的参数转换失败,因为没有类型转换器可以在这些类型之间转换。”}”但据我所知,在我的帖子方法中,我这样写public ActionResult BuildProfile(A obja1) {}
      • 我不知道为什么,但是我会改变这个: Model.MyProperty1.SomeModelType3 .Id, new { @id = "hdfId" })%>只是 Model.MyProperty1.SomeModelType3 .Id)%>。 MVC 需要层次结构的完整路径才能正确绑定。另外,检查 SomeModelType2 是否有一个无参数的构造函数。
      • 嗨 gabnaim,我已经编辑了我的问题,您可以查看示例代码。
      • 好的,我看到一个问题:不要为您的属性提供新的 ID。如果您使用 Html.[something]For,模型绑定器将正确生成名称。只需摆脱所有“新{@id =“hdfAccountId”}”类型代码。
      猜你喜欢
      • 2017-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多