如何在MVC3中绑定嵌套模型?

时间:2011-05-20 03:00:46

标签: asp.net-mvc-3 razor model-binding

我一直在阅读有关UpdateModel()和自定义模型绑定器的所有内容,我仍然无法弄清楚这一点。看起来像这是一个简单的答案。

我有一个名为user的类,我的用户遍布我的MVC Web应用程序。

 public class User
{
    [Key]
    public int ID { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    [Email]
    public string Email { get; set; }

    [Required]
    public string Password { get; set; }

    public virtual ICollection<User> WorkTasks { get; set; }
}

然后是一个在几个地方有它的WorkTask:

public class WorkTask
{
    [Key]
    public int ID { get; set; }
    [Required]
    public string Name { get; set; }
    public  DateTime? DesiredStartDate { get; set; }
    public  DateTime? DesiredEndDate { get; set; }


    public TimeSpan? DesiredTimeSpent { get; set; }

    public virtual ICollection<WorkTaskTag> Tags { get; set; }
    public virtual ICollection<WorkTaskPeriod> Periods { get; set; }

    public virtual ICollection<User> InvolvedUsers { get; set; }
    public virtual User CreatedBy { get; set; }
    public virtual User AssignedTo { get; set; }

    public string UserNameAssignedTo
    {
        get
        {
            if(AssignedTo!=null)
            return AssignedTo.Name;
            return CreatedBy.Name;
        }
    }

    public string TotalTimeSpent { 
        get
        {
            var concretePeriods = Periods
                .Where(i => i.StartDate.HasValue && i.EndDate.HasValue);
            if (concretePeriods != null && concretePeriods.Count() > 0)
            {
                TimeSpan ts = new TimeSpan();
                foreach (var p in concretePeriods)
                {
                    var t=p.EndDate.Value-p.StartDate.Value;
                    ts.Add(t);
                }
                TimePeriodHelpers help = new TimePeriodHelpers();
                return help.GetTimeFormat(ts);
            }
            return "0:00";
        }
    }
}

那么我如何为这个WorkTask创建一个创建模板,允许User类在多个地方绑定到WorkTask?

这是我非常粗暴的尝试:

[HttpPost]
    public ActionResult Create(WorkTask worktask)
    {
        LoadUsers();
        string assignedto=Request["AssignedTo"];
        var user = db.Users.First(i => SqlFunctions.StringConvert((double)i.ID) == assignedto);
        UpdateModel<User>(user);
        if (ModelState.IsValid)
        {
            db.WorkTasks.Add(worktask);
            db.SaveChanges();
            return RedirectToAction("Index");  
        }

        return View(worktask);
    }

和视图:

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>

    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.DesiredStartDate,"Desired Start Date")
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.DesiredStartDate)
        @Html.ValidationMessageFor(model => model.DesiredStartDate)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.DesiredEndDate,"Desired End Date")
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.DesiredEndDate)
        @Html.ValidationMessageFor(model => model.DesiredEndDate)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.DesiredTimeSpent,"Desired Time Spent")
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.DesiredTimeSpent)
        @Html.ValidationMessageFor(model => model.DesiredTimeSpent)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.AssignedTo,"User Assigned To")
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(i=>Model.AssignedTo,(IEnumerable<SelectListItem>)ViewBag.Users)
        @Html.ValidationMessageFor(model => model.AssignedTo)
    </div>
    <p>
        <input type="submit" value="Create" />
    </p>

1 个答案:

答案 0 :(得分:0)

我没有尝试绑定嵌套的User对象,而是基于一个只有UserID的ViewModel创建了表单和控制器。然后我假设如果ViewModel验证正确,那么我可以继续并持久化WorkTask和嵌套的User对象。