3
\$\begingroup\$

I have a standard Edit action in Asp.Net MVC 5 and I want to avoid throwing the unhandled exception when is made a get request without the id like ~/food/edit, so I did this.

public ActionResult Edit(int id = 0)
{
    if (id == 0)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    string result = _foodAppService.GetById(id);
    FoodVm food = string.IsNullOrEmpty(result) 
        ? null 
        : JsonConvert.DeserializeObject<FoodVm>(result);

    if (food == null)
    {
        return RedirectToAction("Index");
    }

    return View(food);
}

My question is: Is it a good practice to handled it in this way or there are more suitable strategies ?

I'm new to this asking question thing, if a should I ask in another way, just let me know, thank you for your time.

\$\endgroup\$
3
\$\begingroup\$

I think "BadRequest" is OK for that case. Alternative options are "PageNotFound" or "redirect to index".

Some other points about your code:

  • 0 is usually a valid ID so I would use -1 as default, even if that is not true in your case.
  • You could check for null or empty first to simplify the code

.

public ActionResult Edit(int id = -1)
{
    if (id < 0)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    string result = _foodAppService.GetById(id);
    if (string.IsNullOrEmpty(result))
    {
        return RedirectToAction("Index");
    }

    var food = JsonConvert.DeserializeObject<FoodVm>(result);
    return View(food);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.