We help IT Professionals succeed at work.

C Sharp new  learner on View model issue

roy_sanu
roy_sanu asked
on
Medium Priority
68 Views
Last Modified: 2020-01-30
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
    if (ModelState.IsValid)
    {
      // work with the model
    }
    // At this point, something failed, redisplay form
    return View(model);
}

Open in new window


Expert please explain me why

One has to validate i.e below

if (ModelState.IsValid)

Open in new window


Can this view object can be used in services structure where business logic resides.
Comment
Watch Question

Chief Technology Ninja
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:

Hi roy_sanu,


Welcome to EE. You can use Code Snippet from the toolbar and it will automatically format your code.


Now, coming to your query, When you decorate your Model properties with various requirements for example, [Required],

ModelState.IsValid will automatically generate appropriate errors and send them back to your View so that you can handle/show the errors.


You can always manipulate your model and still use the incoming data from client.

ModelState.Remove("Offending Property Name");


And then insert appropriate data to continue processing.


Regards,

Chinmay.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.