How to pass a result model object from System.Web.Http.ModelBinding.IModelBinder. Bindmodel?

This is the next question and answer to https://stackoverflow.com/a/318618/

Now that I have been able to successfully retrieve the content, apply deserialization and get the desired object. How to convey it to action? The provided BindModel function should return a bool value, which is very confusing for me.

My code is:

  public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { actionContext.Request.Content.ReadAsStringAsync().ContinueWith(deserialize); return true; } #endregion #region Methods private static void deserialize(Task<string> content) { string formData = content.Result; // {"content":"asdasd","zip":"12321","location":"POINT (1 2)"} Match locationMatch = Regex.Match( formData, @"""location"":""POINT(.+)""", RegexOptions.IgnoreCase | RegexOptions.Singleline); if (!locationMatch.Success) { throw new ModelValidationException("Post data does not contain location part"); } string locationPart = locationMatch.Value; formData = formData.Replace(locationPart, string.Empty); var serializer = new JavaScriptSerializer(); var post = serializer.Deserialize<Post>(formData); post.Location = DbGeography.FromText(locationPart); // how am I supposed to pass `post` to the action method? } 
+2
source share
1 answer

I assume your question is related to the web API (not applicable to ASP.net vnext). The basis for the assumption is the method that you provided in the example, as well as the old question.

  public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { actionContext.Request.Content.ReadAsStringAsync().ContinueWith(deserialize); bindingContext.Model = your model; // You can return from static method or you can pass bindingContext to static method and set model over there. return true; } 

Now about your confusion.

In the Web API, you can register a lot of modelbinder (some of them are registered by default), and some of them are registered and all implement IModelBinder. Therefore, when he tries to analyze the request data, he goes to many connecting devices, and when you return true to BindModel, he will stop there, and the whole module module will be discarded after that.

More detailed information can be found here. (In this you can see the section "Model Associations") http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

+2
source

All Articles