Skip to content

Commit ad4dd52

Browse files
committed
Model Validation has been done with an attribute and source code has been updated with the new way
1 parent f643c70 commit ad4dd52

16 files changed

+26
-3
lines changed
Binary file not shown.
Binary file not shown.

SourceCode/WeatherStackNetCore/Controllers/AutoCompleteController.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,11 +75,12 @@ public IActionResult IndexWithModel(AutoCompleteViewModel? model)
7575
/// <param name="model">Location Search Page Elements</param>
7676
/// <returns>Result Page</returns>
7777
[HttpPost]
78+
[ValidateModel]
7879
public async Task<IActionResult> GetLocationsWithModel(AutoCompleteViewModel model)
7980
{
8081
try
8182
{
82-
if (!ModelState.IsValid) return View("IndexWithModel", model);
83+
// if (!ModelState.IsValid) return View("IndexWithModel", model);
8384

8485
var autoComplete = await CallAutoCompleteFromAPI(model.PlaceName);
8586

SourceCode/WeatherStackNetCore/Controllers/CurrentWeatherController.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,12 @@ public IActionResult IndexWithModel(CurrentWeatherViewModel? model)
7777
/// <param name="model">Current Weather Search Page Elements</param>
7878
/// <returns>Result Page</returns>
7979
[HttpPost]
80+
[ValidateModel]
8081
public async Task<IActionResult> GetCurrentWeatherWithModel(CurrentWeatherViewModel model)
8182
{
8283
try
8384
{
84-
if (!ModelState.IsValid) return View("IndexWithModel", model);
85+
// if (!ModelState.IsValid) return View("IndexWithModel", model);
8586

8687
var currentWeather = await GetCurrentWeatherFromAPI(model.PlaceName, model.Unit, model.Language);
8788

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
using Microsoft.AspNetCore.Mvc;
2+
using Microsoft.AspNetCore.Mvc.Filters;
3+
4+
namespace WeatherStackNetCore.Utils;
5+
6+
/// <summary>
7+
/// Model Validation Attribute Class
8+
/// </summary>
9+
public class ValidateModelAttribute : ActionFilterAttribute
10+
{
11+
/// <summary>
12+
/// In this method, if model is not valid
13+
/// App sends automatically bad request
14+
/// </summary>
15+
/// <param name="context">Context Info</param>
16+
public override void OnActionExecuting(ActionExecutingContext context)
17+
{
18+
if (!context.ModelState.IsValid)
19+
context.Result = new BadRequestResult();
20+
}
21+
}
Binary file not shown.

0 commit comments

Comments
 (0)