HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

An Edit action in ASP.NET MVC, with handling for missing id parameter

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
edithandlingmvcwithactionparameternetformissingasp

Problem

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(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.

Solution

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 (result);
    return View(food);
}

Code Snippets

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);
}

Context

StackExchange Code Review Q#141235, answer score: 3

Revisions (0)

No revisions yet.