Monday, February 21, 2011

ASP.net and CustomModelBinder and a prefix

With the default ModelBinder and its attribute Bind we can set a prefix like this:

public ActionResult Save([Bind(Prefix="test")] Person p)) {

}

I have a CustomModelBinderAttribute which returns a bespoke ModelBinder:

public ActionResult Save([PersonBinderAttribute(Prefix="test2")] Person p)) {

}

How do I access the value of Prefix from within my bespoke model binder?

From stackoverflow
  • I don't believe you can. I'd declare the prefix as a constant at the top of the Controller and just use that.

    private const string c_prefix = "test2";
    public ActionResult Save([PersonBinderAttribute(Prefix=c_prefix)] Person p)) {
        var prefix = c_prefix;
    }
    

    It is my understanding that anything you declare in the Attribute can only be used by the Attribute.

    ListenToRick : I can access the value in the controller! Its within the modelbinder I was stumped with. Its fairly easy to implement however - just add a prefix property to PersonBinderAttribute and then pass the value to the modelbinder as its created - however I was hoping that the framework natively supported prefix annotations for customer binders. It doesnt appear to.
    kim3er : I see where you are coming from. I actually did something similar yesterday with ActionFilterAttribute's, but didn't make the connection with your question.

0 comments:

Post a Comment