0

I need to bind model from request and convert to my custom object, my request data is json and method is post.

This is my method in web api:

public IHttpActionResult Edit([ModelBinder(typeof(KModelBinder))] object data) 

My problem is: I cannot access to json from ValueProvider in modelbinder.

public class KModelBinder : IModelBinder {
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) {
        var valueProvider = bindingContext.ValueProvider;
        var valProviderResult = valueProvider.GetValue("id");
        // ....
    }
}
5
  • if i dont use json, modelbinder detect data, but whene request is json, modelbinder cannot detect data :( Commented Feb 19, 2016 at 14:33
  • Did you tried like this: public IHttpActionResult Edit(MyModelClass data)? It should work out of the box. Commented Feb 19, 2016 at 14:35
  • no! because, this method use for multi models, and i detect model in model binder Commented Feb 19, 2016 at 14:37
  • Why not create a base controller and inherit to other controllers from that base controller. You can make it generic and implement the Edit method like this public IHttpActionResult Edit(T data). If you need more info I'll post it as an aswer. Commented Feb 19, 2016 at 15:19
  • @MihailStancescu please send more info, thanx Commented Feb 19, 2016 at 15:26

1 Answer 1

1

You can try a base controller class like this

public class BaseController<T>: ApiController
{

    //here you can add whatever dependency injection you may use
    public BaseController(DbContext context) 
    {
        _context = context;  
    }

   [HttpPost]
   public IHttpActionResult Add(T data)
   {
       return Ok(_context.Add(data));
   }

   [HttpPut]
   public IHttpActionResult Edit(T data)
   {
        _context.Modify(data); //here depends on your ORM or data access layer
        return Ok(data);
   }

   /*other methods you think are necessary in this base controller*/
}

Afterwards you can define your controllers like this

public class UserController: BaseController<User>
{
   //here you can override the base controller methods
}

I use somewhat similarly approach in my current project and works fine.

Check it out and see if this works for your project.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.