如果用户使用http://www.mysite.com/Quote/Edit而不是http://www.mysite.com/Quote/Edit/1000访问我的网站会怎么样?换句话说,他们没有为{ ID}。 如果他们不这样做,我想显示一个很好的“未找到”页面,因为他们没有给出一个ID。 我currentl通过接受一个可为空的int作为Controller Action中的参数来处理此问题,并且它工作正常。 但是,我很好奇,如果有更标准的MVC框架处理这种方式,而不是我目前使用的代码(见下文)。 是一种更平滑的方式来处理这个问题,或者这是相当简单的方法来做到这一点?
[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"); }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"); }最满意答案
你的其他选择是
有两个Edit操作; 一个以int id作为参数,另一个没有任何参数。 只有将Edit(int id)作为你的动作,并让你的控制器的HandleUnknownAction方法去做你没有找到你的实体时应该做的事情(这有点复杂)。但我最喜欢你的方法,因为它很简单,正确地处理这种情况。
顺便说一句,你不需要这个局部变量,你可以这样做,以获得更好的可读性:
//... if (!id.HasValue) return View("QuoteNotFound"); var viewModel = new QuoteViewModel(this.UserId); viewModel.LoadQuote(id.Value); //...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); //...更多推荐
发布评论