This is a place for tracking feedback and related bugs for scoping future investments in Model Binding.
I'd very much like to see manual model binding possible. I asked a long time go at #4811 and it seems there's still no way to accomplish such a thing without letting go of the advantages that model binding/validation brings.
Making model binding/validation not directly coupled to mvc will also be a super nice thing to have.
My temporary solution:
```C#
public class BaseController : Controller
{
public bool IsAjaxRequest()
{
if (Request == null)
{
throw new ArgumentNullException("request");
}
return Request.Headers["X-Requested-With"] == "XMLHttpRequest";
}
public override async Task<bool> TryUpdateModelAsync(object model, Type modelType, string prefix)
{
if (model == null)
model = Activator.CreateInstance(modelType);
var result = await base.TryUpdateModelAsync(model, modelType, prefix);
if (IsAjaxRequest())
{
try
{
using (var reader = new StreamReader(Request.Body))
JsonConvert.PopulateObject(reader.ReadToEnd(), model);
return true && result;
}
catch (Exception exc)
{
var logger = HttpContext.RequestServices.GetService<ILogger<BaseController>>();
if (logger != null)
logger.LogWarning(exc, "Error occurred while parsing '{0}' model.", modelType.Name);
}
return false;
}
else
{
return result;
}
}
public virtual Task<bool> TryUpdateModelAsync(object model, Type modelType)
{
return TryUpdateModelAsync(model, modelType, null);
}
public override Task<bool> TryUpdateModelAsync<TModel>(TModel model, string prefix)
{
return TryUpdateModelAsync(model, typeof(TModel), prefix);
}
public override Task<bool> TryUpdateModelAsync<TModel>(TModel model)
{
return TryUpdateModelAsync(model, typeof(TModel));
}
}
```
Please correct me if I am doing something weird in the code or there is some better solution.
@rynowak I think that your link to issue about support of binding immutable types is pointing to something unrelated. Anyway this feature would be highly appreciated especially when you design CQRS style API where commands and queries by definition should be immutable. BTW even EntityFramework supports deserializing entity via constructor nowadays so why MVC model binders still require public setters and by doing so discourage good practices like immutable messages/DTOs.
@rynowak, I would very much appreciate this feature. 馃槏 Now that System.Text.Json
supports JsonConstructor
in .net 5.0, it feels incomplete not having the ability for immutable complex types in asp net core.
@rynowak It looks like #1786 Support binding immutable types by binding to the constructor
links to the wrong issue
Most helpful comment
I'd very much like to see manual model binding possible. I asked a long time go at #4811 and it seems there's still no way to accomplish such a thing without letting go of the advantages that model binding/validation brings.
Making model binding/validation not directly coupled to mvc will also be a super nice thing to have.