Still need to TryUpdateModel when posting through Ajax

just wondering if there is any point validating a view model using TryUpdateModel(), when calling a Post method through Ajax. I have the following code which is called via a jquery Ajax post:

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult SubmitForm(ViewModel viewModel)
{
    var valid = TryUpdateModel(viewModel);

    if (valid)
    {
        var service = new Service();
        var result = _tmpRepository.ExecuteService(viewModel));

        return Json(new { Valid = valid, Response = result });
    }
    return Json(new { Valid = valid });
}

The way I see it, I'm using unobtrusive validation with data annotation on my view model. So the only way that validation wouldn't occur is if javascript was disabled and if javascript is disabled my Ajax request isn't going to do a fat lot!

Answers


You still need to validate any data server side. There's nothing stopping someone from submitting the request themselves, or modifying the parameters of the ajax call in the browser. Client side validation should only be a convenience for the user.

You can avoid the TryUpdateModel() though:

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult SubmitForm(ViewModel viewModel)
{  
    if (ModelState.IsValid)
    {
        var service = new Service();
        var result = _tmpRepository.ExecuteService(viewModel));

        return Json(new { Valid = valid, Response = result });
    }

    return Json(new { Valid = valid });
}

Need Your Help

Format an array as string in Python

python irc bots

I'm making a python irc moderation bot.

Difference between onItemClickListener and OnItemSelectedListener of AdapterView

android android-adapterview

What is the difference between these two listeners,documentation says :