0

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?

2
  • Please post some code... Commented Dec 31, 2008 at 12:47
  • yup code would be a good idea, I'm not sure I understand the problem fully. Commented Jan 3, 2009 at 14:01

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.