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

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

I have a FraudDto object that has a child FraudCategory, and I want to set this object from the values โ€‹โ€‹that are submitted from the form.

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

I have the following parent FraudDto object with which I bind to 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; } } 

In the form, I have the following code where I want to associate FraudCategoryDto with a drop-down list. The view has a ViewPage view:

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

Then I have the following controller code:

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

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

Are there any additional steps needed to connect this complex object?

+4
source share
1 answer

The drop-down list returns a single value, so in this case it tries to set a string of values โ€‹โ€‹equal to your complex object. If you do not have an implicit conversion from a string to your object, then what you are trying to do will probably not work.

Any suggestions that may arise to solve this problem will be based on what your method of storing FraudCategoryDto objects, or how you use this information.

+1
source

Source: https://habr.com/ru/post/1305963/


All Articles