Add TryUpdateModelAsync to pages

This commit is contained in:
Ryan Nowak 2017-02-07 21:16:40 -08:00
parent 314aa366e1
commit 9264f3aa2d
2 changed files with 47 additions and 3 deletions

View File

@ -9,10 +9,33 @@ namespace Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure
{
public abstract class PageArgumentBinder
{
public async Task<object> BindModelAsync(PageContext context, Type type, object defaultValue, string name)
public async Task<object> BindModelAsync(PageContext context, Type type, object @default, string name)
{
var result = await BindAsync(context, value: null, name: name, type: type);
return result.IsModelSet ? result.Model : defaultValue;
var result = await BindAsync(context, null, name, type);
return result.IsModelSet ? result.Model : @default;
}
public Task<T> BindModelAsync<T>(PageContext context, string name)
{
return BindModelAsync<T>(context, default(T), name);
}
public async Task<T> BindModelAsync<T>(PageContext context, T @default, string name)
{
var result = await BindAsync(context, null, name, typeof(T));
return result.IsModelSet ? (T)result.Model : @default;
}
public async Task<bool> TryUpdateModelAsync<T>(PageContext context, T value)
{
var result = await BindAsync(context, value, string.Empty, typeof(T));
return result.IsModelSet && context.ModelState.IsValid;
}
public async Task<bool> TryUpdateModelAsync<T>(PageContext context, T value, string name)
{
var result = await BindAsync(context, value, name, typeof(T));
return result.IsModelSet && context.ModelState.IsValid;
}
protected abstract Task<ModelBindingResult> BindAsync(PageContext context, object value, string name, Type type);

View File

@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
@ -45,6 +46,26 @@ namespace Microsoft.AspNetCore.Mvc.RazorPages
public ViewDataDictionary ViewData => PageContext?.ViewData;
protected Task<T> BindAsync<T>(string name)
{
return Binder.BindModelAsync<T>(PageContext, name);
}
protected Task<T> BindAsync<T>(T @default, string name)
{
return Binder.BindModelAsync<T>(PageContext, @default, name);
}
protected Task<bool> TryUpdateModelAsync<T>(T value)
{
return Binder.TryUpdateModelAsync<T>(PageContext, value);
}
protected Task<bool> TryUpdateModelAsync<T>(T value, string name)
{
return Binder.TryUpdateModelAsync<T>(PageContext, value, name);
}
protected IActionResult Redirect(string url)
{
return new RedirectResult(url);