MVC模型子对象在HTTP帖子上为null [英] MVC Model child object null on HTTP post

查看:74
本文介绍了MVC模型子对象在HTTP帖子上为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望有人可以帮助我.我是MVC的新手,来自winforms/console/vb6background.

Hope someone can help me. I am new to MVC, coming from a winforms/console/vb6background.

很抱歉,如果我已经回答了这个问题,那么我将努力了解如何解决以下问题.

Apologies if this has already been answered, I am stuggling to understand how I can resolve the below issue.

我有一个视图模型:

public class testvm
{
    public int id { get; set; }
    public DateTime date { get; set; }
    public student studentID { get; set; }

    public testvm() { }

    public testvm (student s)
    {
        studentID = s;
    }
}

在将其传递到视图之前,我正在预先填充此ViewModel的学生子对象.

I am pre-populating the student child object of this ViewModel before it is passed to the view.

学生模型:

public class student
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }
}

我遇到的问题是,当模型返回到create HTTP post方法时,学生子对象为空.

The problem I have is when the model is returned to the create HTTP post method the student child object is blank.

控制器代码:

// GET: testvms/Create
public ActionResult Create(int sId)
{
    student a = db.students.Find(sId);

    testvm b = new testvm(a);

    return View(b);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id,date,student")] testvm testvm)
{
    if (ModelState.IsValid)
    {
        db.testvws.Add(testvm);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(testvm);
}

查看代码:

@model WebApplication2.Models.testvm

@{
ViewBag.Title = "Create";
}

<h2>Create</h2>


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

<div class="form-horizontal">
    <h4>testvm</h4>
    <hr />


    @Html.HiddenFor(model => model.studentID.ID)

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.date, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.date, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.date, "", 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")
}

使用学生信息填充视图上的模型对象.将其传递回Create POST控制器后,学生子对象为null!

The model object on the view is populated with the student information. When this is passed back to Create POST controller the student child object is null!

有人可以告诉我我要去哪里哪里或实现这一目标的正确方法吗?

Can somebody please advise where I am going wrong or of the correct way to achieve this?

我的应用程序将具有许多形式,所有形式都需要预先填充学生信息.每个学生都会有很多表格需要填写.

My application will have many forms that will all need to be pre-populated with student information. Each student will have many forms that will need to be filled out for them.

非常感谢, 罗布

推荐答案

对于域模型中的每个属性(在您的情况下是testvm),您的视图(或HiddenFor for ID或其他非用户ui数据).在MVC中,这可能是一种痛苦的绑定嵌套模型,因为DefaultModelBinder可能无法绑定整个对象.但是,在

For every property in domain model (in your case testvm) you must have an EditorFor or Input element (like TextBoxFor or so) on your view(or HiddenFor for ID or other non user ui data).It may be a pain binding nested models in MVC as the DefaultModelBinder may not be able to bind whole object.However it would be safer approach to expose only the required properties on view like

@Html.HiddenFor(model => model.studentID.ID)
@Html.HiddenFor(model => model.studentID.Name)

以及稍后在控制器端

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(testvm testvm)
{
  var originalobj=db.get //get fresh copy from data store
 originalobj.Name=testvm.Name;
//     ...other properties
//perform required operations on originalobj
}

您可以将AutoMapper用于此目的

you may use AutoMapper for this Purpose as

Mapper.CreateMap<testvm,testvm>();
originalobj=Mapper.Map<testvm,testvm>(testvm,originalobj);

您可能会在以下位置找到有关Automapper的更多信息: https://github.com/AutoMapper/AutoMapper/wiki/入门

you may find more information about Automapper on : https://github.com/AutoMapper/AutoMapper/wiki/Getting-started

这篇关于MVC模型子对象在HTTP帖子上为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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