07. CSharp ASP NET Core Working With Data
07. CSharp ASP NET Core Working With Data
Model Binding
– Custom Model Binding
Model Validation
– Custom Model Validation
Working with Files
– Upload and Download Files
2
MODEL BINDING
3
Model Binding
• Model binding in ASP.NET Core MVC maps data from HTTP requests to
action method parameters.
– The parameters may be primitive types or complex types
– Implemented abstractly, paving the way for reusability in different apps
• The framework binds request data to action parameters by name
– The value of each parameter will be searched, using the parameter name
– Classes are mapped using the names of the public settable properties
• Model binding can look through several data sources per Request
– Form values – POST Request parameters
– Route values – The set of Route values provided by the Routing
– Query strings – The query string parameters in the URL
– Even in headers, cookies, session, etc. in custom model binders
– Data from these sources are stored as name-value pairs
• The framework checks each of the data sources for a parameter value
– If there is no parameter in the data source, the next in order is checked
– The data sources are checked in the order specified above
5
Incoming Request to MVC
6
Model Binding
7
Model Binding
return Ok("Success!");
}
}
8
Model Binding
[From{source}] Used to specify the exact binding source. [FromHeader], [FromQuery], [FromRoute],
[FromForm]
[FromServices] Uses dependency injection to bind parameters from services.
[FromBody] Use configure formatters to bind data from request body. Formatter is selected based
on Content-Type of Request.
[ModelBinder] Used to override the default model binder, binding source and name.
9
Custom Model Binder
10
Custom Model Binder
return null;
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.ModelBinderProviders
.Insert(0, new StudentEntityBinderProvider()); // Add custom binder to
beginning
});
} 11
MODEL VALIDATION
12
Model Validation
14
Model Validation
[StringLength] Validates that a string property has at most the given maximum length.
15
Custom Model Validation
• Validation attributes work for most needs, but not for all
– Sometimes you need to implement your own validation attributes
public class IsBefore : ValidationAttribute
{
private const string DateTimeFormat = "dd/MM/yyyy";
private readonly DateTime date;
[Required]
[StringLength(20)]
public string Password { get; set; }
[Required
public string FirstName { get;
set; }
[Required
public string LastName { get; set; }
[IsBefore("01/01/2000")]
public DateTime BirthDate { get;
set; }
17
}
Custom Model Validation
ModelBinderProvider 1
19
FILES
20
Uploading Files
• ASP.NET Core MVC supports File Upload using simple model binding
– For larger files, Streaming is used
<form method="post" enctype="multipart/form-data"
asp-controller="Files" asp-
action="Upload">
<input type="file" name="file">
<button type="submit" value="Upload" />
</form>
• When uploading files using model binding, your action should accept:
– IFormFile (for single file) or IEnumerable<IFormFile> (or List<IFormFile>)
[HttpPost("Upload")]
public async Task<IActionResult> Upload(List<IFormFile> files)
{
var filePath = Path.GetTempFileName(); // Full path to file in temp
location
23
Downloading Files