Frage

Ich habe mein eigenes Modell Binder erstellt ein Abschnitt definierte Dropdownlist aus meiner Sicht zu behandeln wie:

Html.DropDownListFor(m => m.Category.Section, new SelectList(Model.Sections, "SectionID", "SectionName"), "-- Please Select --")

Und hier ist mein Modell Binder:

public class SectionModelBinder : DefaultModelBinder 
{ 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 

        if (bindingContext.ModelType.IsAssignableFrom(typeof(Section)) && value != null) 
        { 
            if (Utilities.IsInteger(value.AttemptedValue)) 
                return Section.GetById(Convert.ToInt32(value.AttemptedValue)); 
            else if (value.AttemptedValue == "")
                return null; 
        } 

        return base.BindModel(controllerContext, bindingContext); 
    } 
}

Jetzt in meinem Controller kann ich nur sagen:

[HttpPost]
public ActionResult Create(FormCollection collection)
{
    var category = new Category();

    if (!TryUpdateModel(category, "Category")
        return View(new CategoryForm(category, _sectionRepository().GetAll()));

    ...
}

Dies bestätigt schön und der korrekte Wert für den Abschnitt zugewiesen wird, wenn das Modell aktualisiert wird, aber es nicht den richtigen Wert wählen, wenn eine andere Eigenschaft nicht validieren.

Ich würde es begrüßen, wenn jemand mir zeigen konnte, wie dies zu tun. Dank

War es hilfreich?

Lösung

gelöst Problem mit den Worten:

Html.DropDownListFor(m => m.Category.Section, new SelectList(Model.Sections.Select(s => new { Text = s.SectionName, Value = s.SectionID.ToString() }), "Value", "Text"), "-- Please Select --") 

Das Problem scheint der Abschnitt drehen sich um eine ganze Zahl zu sein. Wenn Sie es in einen String konvertieren funktioniert alles einwandfrei. Hoffe, das hilft.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top