1

I've got a View where I use a naming-convention on my text-fields, to indicate what should be done with the content once it is posted back to my controller.

The format is similar to:

<input type="text" name="RegistrationLine#ID" /> for updates

<input type="text" name="CreateRegistrationLine#LineNumber" /> for create

Now since I'm using this Naming-convention, regular model-binding isn't possible. But I've been reading up a bit on the subject and did find a bit of an indication that it would be possible to write a custom model binder, that should be able to help parse and bind these form elements and instantiate the objects correctly.

Please read: Bind formValue to property of different name, ASP.NET MVC

This is a bit similar to what I am doing except, I have the additional complexity of having appended information in the formelement-name that I am trying to bind to.

Am I way off base here? and if not, can any of you drop a few lines of code to show how you would start this model-binder off..

If this is a very bad approach to what I am really trying to achieve, I would love to hear suggestions for better approaches. Just note that what I want to be able to do is post back both updates and creates in one go.

3
  • 1
    I have to ask "why?". If you replaced # with . you could take advantage of the default model binder and save yourself a lot of work. Commented Dec 17, 2009 at 2:44
  • Maybe the View Model Pattern will be the way to go in this case, as implementing a custom ModelBinder is not that simple, specially if you want it to do more that just bind. Commented Dec 17, 2009 at 3:17
  • @jfar: That's interesting. So that means I am missing some understanding of the default binder. Commented Dec 17, 2009 at 4:55

1 Answer 1

0

I kinda have to agree with @jfar and @omar. I don't think a custom model binder is where you want to be in this instance.

You can pass a complex type to your view and simply use the full stop like @jfar mentioned.

id="Model.Person.Name.FirstName" will happily bind to an object named Person that has a class in it called Name that has a property called FirstName.

Now if you want to do some special checks on the data you could implement a partial class which would do the validations etc and populate the ModelState errors.

public partial class Name
{
  public void Validate(){ }
  public int CreateRegistrationLine(){ }
  public bool DoSpecialActions(){ }
}

It's a little unclear what your special actions are doing so my example above may not be what you want.

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

Comments

Your Answer

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