views:

1005

answers:

1

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

+1  A: 

A drop down list returns a single value, so in this case, it is trying to set the value string equal to your complex object. Unless you have a implicit conversion from string to your object, what you are trying to do will probably not work.

Any suggestions I could have for how to work around this problem are going to be based on what your method for storing FraudCategoryDto objects is, or how you are using that information.

NickLarsen
This works:<%= Html.DropDownListFor(x => x.FraudCategory.Id,Model.FraudCategoryList, new { Style = "width:200px" })%>I am setting the value of the child object.As usual, all the examples are only working with simple objects.
dagda1
Ahh good call on that solution, that skipped my mind completely. I was about to suggest using a repository. It looks like that does not load the category name field though.
NickLarsen