2

I have a custom class

public class BloggerViewModel
{        
    public Person Blogger;
    public List<BloggerWebsite> BloggerWebsites;
}

That I pass into a view

[HttpGet]
    public ActionResult Edit(int id)
    {
        blogger = GetById(id);            
        var WebSites = GetBloggersWebsites(Id);            
        var BloggerViewModel = new BloggerViewModel();
        BloggerViewModel.Blogger = blogger;
        BloggerViewModel.BloggerWebsites = WebSites;
        return View(BloggerViewModel);
    }

Then when I post back to the edit action

[HttpPost]
public ActionResult Edit(BloggerViewModel entity)
{
    return View(entity);
}

entity is null.

My view is something like this ( I took out allot of the code that you didn't need to see. Such as most of the text box bindings)

@model Bloginect.Model.Models.BloggerViewModel

<h2>Edit</h2>

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

<fieldset>
    <legend>Person</legend>

    @Html.HiddenFor(model => model.Blogger.Id)

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

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

        <div class="editor-field">

            @if (Model.BloggerWebsites[0].Website != null)
            {
                Html.EditorFor(model => model.BloggerWebsites[0].Website);
            }
            else
            {
                @Html.TextBox("Website1")
            }

        </div>

        <div class="editor-field">
            @if (Model.BloggerWebsites[1].Website != null)
            {
                Html.EditorFor(model => model.BloggerWebsites[0].Website);
            }
            else
            {
                @Html.TextBox("Website2")
            }
        </div>

        <div class="editor-field">
            @if (Model.BloggerWebsites[2].Website != null)
            {
                Html.EditorFor(model => model.BloggerWebsites[0].Website);
            }
            else
            {
                @Html.TextBox("Website3")
            }          
        </div>

    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>
}

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

Is there something I am doing wrong? I have checked out some of the other replies to similar questions on this and they did not answer my question.

4

1 回答 1

0

您必须使用编辑器来处理对嵌套模型属性的绑定,可以在此处找到有关如何执行此操作的一个很好的示例。

于 2013-05-04T11:16:56.490 回答