Html.DropDownListFor<> and complex object in ASP.NET MVC2

Posted by dagda1 on Stack Overflow See other posts from Stack Overflow or by dagda1
Published on 2010-04-04T12:29:22Z Indexed on 2010/04/04 12:33 UTC
Read the original article Hit count: 1042

Filed under:
|
|
|

Hi,

I am looking at ASP.NET MVC2 and trying to post a complex object using the new EditorFor syntax.

I have a FraudDto object that has a FraudCategory child object and I want to set this object from the values that are posted from the form.

Posting a simple object is not a problem but I am struggling with how to handle complex objects with child objects.

I have the following parent FraudDto object whcih I am binding to on the form:

public class FraudDto
{
    public FraudCategoryDto FraudCategory { get; set; }

    public List<FraudCategoryDto> FraudCategories { get; private set; }

    public IEnumerable<SelectListItem> FraudCategoryList
    {
        get
        {
            return FraudCategories.Select(t => new SelectListItem
            {
                Text = t.Name,
                Value = t.Id.ToString()
            }); 

        }

The child FraudCategoryDto object looks like this:

public class FraudCategoryDto
{
    public int Id { get; set; }

    public string Name { get; set; }
}

On the form, I have the following code where I want to bind the FraudCategoryDto to the dropdown. The view is of type ViewPage:

<td class="tac">
    <strong>Category:</strong>
</td>
<td>
    <%= Html.DropDownListFor(x => x.FraudCategory, Model.FraudTypeList)%>
</td>

I then have the following controller code:

[HttpPost] 
public virtual ViewResult SaveOrUpdate(FraudDto fraudDto)
{
    return View(fraudDto);
}

When the form is posted to the server, the FraudCategory property of the Fraud object is null.

Are there any additional steps I need to hook up this complex object?

Cheers

Paul

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about mvc2