views:

786

answers:

2

I'm using asp.net mvc and I'm trying to create a new Employee, in my form I use the Html.DropDown(...) to display a list of Departments to select from.

Ideally I would like MVC to just figure out which Department was selected (Id property is the value in dropdown), fetch it and set it in the incoming Employee object. instead I get a null value and I have to fetch the Department myself using the Request.Form[...].

I saw an example here: http://blog.rodj.org/archive/2008/03/31/activerecord-the-asp.net-mvc-framework.aspx but that doesn't seem to work with asp.net mvc beta

This is basic CRUD with a well-proven ORM.... need it really be so hard?

A: 

I ported ARFetch to ASP.NET MVC a couple of weeks ago... maybe that could help you.

Mauricio Scheffer
A: 

ASP.NET MVC does not know how to translate the DepartmentId form value to a Department.Load(DepartmentId) call. To do this you need to implement a binder for your model.

[ActiveRecord("Employees")]
[ModelBinder(EmployeeBinder]
public class Employee : ActiveRecordBase<Employee>
{
    [PrimaryKey]
    public int EmployeeId
    {
        get;
        set;
    }

    [BelongsTo(NotNull = true)]
    public Department Department
    {
        get;
        set;
    }

    // ...
}

The EmployeeBinder is responsible for turning route/form data into an object.

public class EmployeeBinder : IModelBinder
{
    #region IModelBinder Members

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // ...

        if (controllerContext.HttpContext.Request.Form.AllKeys.Contains("DepartmentId"))
        {
            // The Department Id was passed, call find
            employee.Department = Department.Find(Convert.ToInt32(controllerContext.HttpContext.Request.Form["DepartmentId"]));
        }
        // ...
    }

    #endregion
}

With this in place anytime an Employee is used as a parameter for an action the binder will be called.

public ActionResult Create(Employee employee)
    {
        // Do stuff with your bound and loaded employee object!
    }

See This blog post for further information

JHappoldt