只是在将模型数据从视图传递到控制器时获取空值

时间:2017-08-23 12:42:10

标签: asp.net-mvc

我刚用MVC.NET框架创建了一个组合模型,并将它从我的视图传递给控制器​​并获得了空值:

型号:

namespace MyApp.Models
{
    public class ModelX
    {
        public String attributeX { set; get; }
    }
}

namespace MyApp.Models
{
    public class ModelY
    {
        public String attributeY { set; get; }
    }
}

namespace MyApp.Models
{
    public class MyComposedModel
    {
        public ModelX SubModel1 { set; get; }
        public ModelY SubModel2 { set; get; }
    }
}

CreateView的:

@model Repo.Models.MyComposedModel

@{
    ViewBag.Title = "Create";
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.SubModel1.attributeX, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.SubModel1.attributeX, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.SubModel1.attributeX, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.SubModel2.attributeY, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.SubModel2.attributeY, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.SubModel2.attributeY, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

控制器:

//... 

public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(MyComposedModel MCM)
        {
            if (ModelState.IsValid)
            {
                ModelX modX = new ModelX();

                modX.attributeX = MCM.SubModel1.attributeX;

                db.ModelX.Add(modX);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(MCM);
        }

//...

愿你能帮助我找出我的错误所在。对不起,我是新手。我希望我不会以完全错误的方式做到这一点。最好的问候和提前感谢!

1 个答案:

答案 0 :(得分:0)

试试这个

namespace MyApp.Models
{
    public class MyComposedModel
    {
        public MyComposedModel()
        {
            SubModel1 = new ModelX();
            SubModel2 = new ModelY();
        }

        public ModelX SubModel1 { set; get; }
        public ModelY SubModel2 { set; get; }
    }
}

如果MVC无法自动初始化这些子模型。