Asp.net mvc + activerecord saving object graph

I am using asp.net mvc and I am trying to create a new Employee, in my form I am using Html.DropDown (...) to display a list of departments to select.

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

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

It's a basic CRUD with a well proven ORM .... is it really that hard?

0


source to share


2 answers


ASP.NET MVC doesn't know how to translate the form value DepartmentId to call Department.Load (DepartmentId). To do this, you need to inject 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;
    }

    // ...
}

      

EmployeeBinder is responsible for converting route / form data to 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
}

      



That being said, anytime Employee is used as a parameter to an action to be called by the binder.

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

      

See this blog post for further details

+1


source


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



0


source







All Articles