简体   繁体   English

当我在asp.net mvc控制器操作中验证失败时,如何保留我的URL

[英]how can i keep my url when my validation fail in asp.net mvc controller action

if i start off on a Detail page: 如果我从详细信息页面开始:

http:\\www.mysite.com\App\Detail

i have a controller action called Update which normally will call redirectToAction back to the detail page. 我有一个名为Update的控制器操作,通常会将redirectToAction调用回详细信息页面。 but i have an error that is caught in validation and i need to return before redirect ( to avoid losing all of my ModelState ). 但我有一个错误,在验证中被捕获,我需要在重定向之前返回( 以避免丢失我的所有ModelState )。 Here is my controller code: 这是我的控制器代码:

 public override ActionResult Update(Application entity)
    {
        base.Update(entity);
        if (!ModelState.IsValid)
        {
            return View("Detail", GetAppViewModel(entity.Id));
        }
      return RedirectToAction("Detail", new { id = entity.Id }) 

but now I see the view with the validation error messages (as i am using HTML.ValidationSummary() ) but the url looks like this: 但现在我看到带有验证错误消息的视图(因为我正在使用HTML.ValidationSummary())但是url看起来像这样:

http:\\www.mysite.com\App\Update

is there anyway i can avoid the URL from changing without some hack of putting modelstate into some temp variables? 无论如何,我可以避免更改URL而没有将模型状态放入某些临时变量的黑客攻击? Is there a best practice here as the only examples i have seen have been putting ModelState in some tempdata between calling redirectToAction . 这里有一个最佳实践,因为我见过的唯一例子是在调用redirectToAction之间将ModelState放入一些tempdata中

As of ASP.NET MVC 2, there isn't any such API call that maintains the URL of the original action method when return View() is called from another action method. 从ASP.NET MVC 2开始,没有任何此类API调用在从另一个操作方法调用return View()时维护原始操作方法的URL。

Therefore as such, the recommended solution and a generally accepted convention in ASP.NET MVC is to have a corresponding, similarly named action method that only accepts a HTTP POST verb. 因此,推荐的解决方案和ASP.NET MVC中普遍接受的约定是具有相应的,类似命名的动作方法,该方法仅接受HTTP POST动词。 So in your case, having another action method named Detail like so should solve your problem of having a different URL when validation fails. 因此,在您的情况下,如果有另一个名为Detail操作方法,则可以解决在验证失败时使用不同URL的问题。

[HttpPost]
public ActionResult Detail(Application entity)
{
    base.Update(entity);
    if (ModelState.IsValid)
    {
        //Save the entity here
    }
   return View("Detail", new { id = entity.Id });
}  

This solution is in line with ASP.NET MVC best practices and also avoids having to fiddle around with modestate and tempdate . 此解决方案符合ASP.NET MVC最佳实践,并且还避免了使用modestatetempdate

In addition, if you haven't explored this option already then client side validation in asp.net mvc might also provide for some solution with regards to your URL problem. 此外,如果您尚未探索此选项,那么asp.net mvc中的客户端验证可能也会针对您的URL问题提供一些解决方案。 I emphasize some since this approach won't work when javascript is disabled on the browser. 我强调一些,因为这种方法在浏览器上禁用javascript时不起作用。

So, the best solution would be have an action method named Detail but accepting only HTTP POST verb. 因此,最好的解决方案是使用名为Detail的操作方法,但只接受HTTP POST动词。

The problem here is actually caused by your implementation. 这里的问题实际上是由您的实现引起的。 This doesn't answer your question, but it describes where you've gone wrong in the first place. 这不能回答你的问题,但它首先描述了你出错的地方。

If you want a page that is used to update or edit an item, the URL should reflect this. 如果您需要用于更新或编辑项目的页面,则URL应反映此情况。 For example. 例如。

You visit http:\\www.mysite.com\\App\\Detail and it displays some information about something. 您访问http:\\ www.mysite.com \\ App \\ Detail,它会显示有关某些内容的信息。 That is what the URL describes it is going to do. 这就是URL描述它将要做的事情。 In your controller, the Detail() method would return the Detail.aspx view. 在您的控制器中,Detail()方法将返回Detail.aspx视图。

To edit an item, you would visit http:\\www.mysite.com\\App\\Edit and change the information you wish to update, the form would post back to the same URL - you can handle this in the controller with these methods: 要编辑项目,您将访问http:\\ www.mysite.com \\ App \\ Edit并更改您要更新的信息,表单将回发到相同的URL - 您可以使用以下方法在控制器中处理:

[HttpGet]
public ActionResult Edit() {
    MyModel model = new MyModel();
    ...
    return View(model);
}

[HttpPost]
public ActionResult Edit(MyModel model) {
    ...
    if (ModelState.IsValid) {
        // Save and redirect
        ...
        return RedirectToAction("Detail");
    }
    return View(model);
}

If you ever find yourself doing this... 如果你发现自己这样做......

return View("SomeView", model);

You are making your own life harder (as well as breaking the principles behind URLs). 你正在努力改变自己的生活(以及打破网址背后的原则)。

If you want to re-use part of a view, make it a partial view and render it inside of the view that is named after the method on the controller. 如果要重新使用视图的一部分,请将其设置为局部视图,并将其呈现在以控制器上的方法命名的视图内。

I apologise that this potentially isn't very helpful, but you are falling into an MVC anti-pattern trap by displaying the same view from a differently named method. 我很抱歉这可能不是很有用,但是你会通过从不同命名的方法显示相同的视图而陷入MVC反模式陷阱。

As @Malcolm sais, best practice is to put ModelState in TempData , but don't do it manually ! 作为@Malcolm sais, 最佳做法是将ModelState放在TempData ,但不要手动执行 If you'd do this manually in every controller action where it's relevant, you would introduce immense amounts of repeated code, and increase the maintenance cost vastly. 如果您在每个相关的控制器操作中手动执行此操作,则会引入大量重复代码,并大大增加维护成本。

Instead, implement a couple of attributes that do the job for you. 相反,实现一些为您完成工作的属性 Kazi Manzur has an approach (scroll down to the end of the post) that has been widely spread, and Evan Nagle shows an implementation with tests that is essentially the same as Kazi's, but with different names. Kazi Manzur有一种广泛传播的方法 (向下滚动到帖子的末尾),Evan Nagle展示了一种 Kazi's基本相同但具有不同名称的测试实现。 Since he also provides unit tests that make sure the attributes work, implementing them in your code will mean little or no maintenance cost. 由于他还提供了确保属性有效的单元测试,因此在代码中实现它们意味着很少或根本没有维护成本。 The only thing you'll have to keep track of is that the controller actions are decorated with the appropriate attributes, which can also be tested. 您必须要跟踪的唯一事情是控制器操作使用适当的属性进行修饰,这些属性也可以进行测试。

When you have the attributes in place, your controller might look something like this (I deliberately simplified, because I don't know the class you inherit from): 当你有适当的属性时,你的控制器可能看起来像这样(我故意简化,因为我不知道你继承的类):

[HttpPost, PassState]
public ActionResult Update(EntityType entity)
{
    // Only update if the model is valid
    if (ModelState.IsValid) {
        base.Update(entity);
    }
    // Always redirect to Detail view.
    // Any errors will be passed along automagically, thanks to the attribute.
    return RedirectToAction("Detail", new { id = entity.Id });
}

[HttpGet, GetState]
public ActionResult Detail(int id)
{
    // Get stuff from the database and show the view
    // The model state, if there is any, will be imported by the attribute.
}

You mention that you feel putting ModelState in TempData feels like a "hack" - why? 你提到你觉得把ModelState放在TempData就像是“黑客” - 为什么? I agree with you that doing it with repeated code in every single controller action seems hacky, but that's not what we're doing here. 我同意你的观点,在每一个控制器动作中重复执行代码看起来很糟糕,但这不是我们在这里做的。 In fact, this is exactly what TempData is for . 实际上, 这正是TempData的用途 And I don't think the above code looks hacky... do you? 我不认为上面的代码看起来很丑陋......是吗?

Although there are solutions to this problem that might appear simpler, such as just renaming the action method to preserve the URL, I would strongly advise against that approach. 虽然这个问题的解决方案可能看起来更简单,例如只是重命名动作方法以保留URL,但我强烈反对这种方法。 It does solve this problem, but introduces a couple of others - for example, you'll still have no protection against double form submission, and you'll have pretty confusing action names (where a call to Detail actually changes stuff on the server). 它确实解决了这个问题,但介绍了其他几个问题 - 例如,你仍然没有防止双重表单提交的保护,你将会有相当混乱的动作名称(其中对Detail的调用实际上改变了服务器上的内容) 。

The best practice you ask for is actually what you explained not to do: putting modelstate into tempdata. 你要求的最佳实践实际上是你解释不要做的事情:将模型状态放入tempdata。 Tempdata is meant for it, that's why I would not call it a hack. Tempdata意味着它,这就是我不称之为黑客的原因。

If this is to much repetitive code you could use the attribute modeldatatotempdata of MVCContrib. 如果这是重复的代码,您可以使用MVCContrib的属性modeldatatotempdata。 But the store is still TempData. 但商店仍然是TempData。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何基于ASP.NET MVC中的控制器操作在页面javascript中设置变量? - How can I set a variable in my pages javascript based on my controller action in ASP.NET MVC? 在 ASP.net MVC 中,我可以在完成 controller 操作之前处理我的 cshtml 逻辑吗? - In ASP.net MVC Can I process through my cshtml logic before finishing the controller action? Asp.net MVC 4 razor如何在视图中保存列表时如何在控制器中保留类型 - Asp.net mvc 4 razor How keep types in my Controller when saving a list in a view 如何在ASP.NET MVC 5.1项目中通过控制器的动作使用标准JSON格式器? - How can I use the standard JSON formatter from an action of my controller in an ASP.NET MVC 5.1 project? 给定一个URL和HTTP动词,如何在ASP.NET MVC / Web API中解析控制器/动作? - Given a URL and HTTP verb, how can I resolve the controller/action in ASP.NET MVC/Web API? 如何将对象从我的视图传递到 ASP.NET MVC 中的控制器? - How can I pass an object from my view to my controller in ASP.NET MVC? 如何使用asp.net mvc在视图中为控制器中的每个动作创建动作链接? - How do I create an action link for each action in my controller within a view using asp.net mvc? ASP.NET MVC:如何让我的业务规则验证冒泡到表示层? - ASP.NET MVC: How can I get my business rule validation to bubble up to the presentation layer? 如何在ASP.NET MVC3中的URL中替换_? - How can I replace _ with - in my URL in ASP.NET MVC3? MVC ASP.NET提交给Controller时在View中获取ViewData.Model - MVC ASP.NET Getting back my ViewData.Model in my View when I submit to a Controller
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM