简体   繁体   English

返回新视图时如何保留网址

[英]How to preserve url when returning new View

A beginner question - I have a HomeController, HomeModel and HomeView. 一个初学者的问题-我有一个HomeController,HomeModel和HomeView。 When the user comes to the http://page/Home page, then Index method is executed and he can fill out some controls. 当用户访问http://page/Home页面时,将执行Index方法,并且他可以填写一些控件。 After he clicks on a button (postback), the Process action is executed and in the case of an error, the application calls the ModelState.AddModelError method. 他单击按钮(回发)后,将执行Process操作,如果发生错误,应用程序将调用ModelState.AddModelError方法。 Then the Index action is called again and I can display the error on the page. 然后再次调用Index操作,我可以在页面上显示错误。

This works OK, but the problem is that after the postback the new url is http://page/Home/Index instead of http://page/Home . 这可以正常工作,但是问题是回发后新的URL是http://page/Home/Index而不是http://page/Home Any idea how to prevent this? 任何想法如何防止这种情况?

PS - I tried this solution but then the new url was something like http://page/Home?...long string of serialized ModelState data... PS-我尝试了这种解决方案,但是新的URL类似于http://page/Home?...long string of serialized ModelState data...

My Controller: 我的控制器:

[HttpGet]
public ActionResult Index(MyModel model)
{
    return View(model);
}

[HttpPost]
public ActionResult Process(MyModel model)
{
    if (...error...)
    {
        model.SetErrorState();
        ModelState.AddModelError("ProcessError", "error message");
        return View("Index", model);
    }
    else
    {
        // do something...
        model.SetSuccessState();
        return View("Index", model);
    }
}

The problem is you're pushing to a new URL for the HttpPost action. 问题是您要为HttpPost操作推送新的URL。 If you change this to a HttpPost version of your Home Action you can neatly return to the page without the URL changing on error. 如果将其更改为Home Action的HttpPost版本,则可以整洁地返回到该页面,而URL不会因错误而更改。

eg 例如

[HttpGet]
public ActionResult Index(ImportData model)
{
    return View(model);
}

[HttpPost]
public ActionResult Index(MyModel model, FormCollection data)
{
    if (...error...)
    {
        model.SetErrorState();
        ModelState.AddModelError("ProcessError", "error message");
        return View(model);
    }
    else
    {
        // do something...
        model.SetSuccessState();
        return View(model);
    }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM