Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle null {id} on route?

What if a user hits my site with http://www.mysite.com/Quote/Edit rather than http://www.mysite.com/Quote/Edit/1000 In other words, they do not specify a value for {id}. If they do not, I want to display a nice "Not Found" page, since they did not give an ID. I currentl handle this by accepting a nullable int as the parameter in the Controller Action and it works fine. However, I'm curious if there a more standard MVC framework way of handling this, rather than the code I presently use (see below). Is a smoother way to handle this, or is this pretty mush the right way to do it?

    [HttpGet]
    public ActionResult Edit(int? id)
    {
        if (id == null)
            return View("QuoteNotFound");

        int quoteId = (int)id;

        var viewModel = new QuoteViewModel(this.UserId);
        viewModel.LoadQuote(quoteId);
        if (viewModel.QuoteNo > 0)
        {
            return View("Create", viewModel.Quote.Entity);
        }
        else
            return View("QuoteNotFound");
    }
like image 344
MattSlay Avatar asked Nov 05 '22 15:11

MattSlay


1 Answers

Your other options would be

  • Having two Edit actions ; One with int id as its parameters and another without any parameters.
  • Only having Edit(int id) as your action and letting your controller's HandleUnknownAction method to do what it's supposed to do when your entity is not found (this is a bit more complicated).

But I like your approach the best, as it's simple and correctly handles the situation.

BTW, you don't need that local variable, you can just do this for better readability :

//...
if (!id.HasValue)
    return View("QuoteNotFound");

var viewModel = new QuoteViewModel(this.UserId);
viewModel.LoadQuote(id.Value);
//...
like image 131
Çağdaş Tekin Avatar answered Nov 14 '22 11:11

Çağdaş Tekin