MVC 4 RedirectToAction with Model(或返回到旧URL的东西)



我有一个表单,它有多种标准选项,比如按日期范围或特定时期等进行搜索

我的控制器:

public ActionResult Index()
{
    Report model = new Report();
    //assigning default values, default actions, default everything
    //Index.cshtml exists
    return View(model);
}
[HttpPost]
public ActionResult GetByDateRange(Report fromPage)
{
    fromPage.DoWhatItMust();
    //"GetByDateRange.cshtml" doesn't exist, so I send back to Index
    return View("Index", fromPage);
}
[HttpPost]
public ActionResult GetByASpecificDate(Report fromPage)
{
    fromPage.DoWhatYouMustAgain();
    //"GetByASpecifiDate.cshtml" doesn't exist as well, so I send back to Index    
    return View("Index", fromPage);
}

这是可行的,但问题是从localhost:10500/Project/Reportlocalhost:10500/Project/Report/GetByASpecificDate的URL。

有没有我可以保留主的还是索引的?

我尝试了RedirectToAction,但它不接受模型作为参数,所以我不知道如何保留主URL,但根据用户输入调用不同的方法。

您可以用[ActionName("Index")]装饰其中一个"GetBy"方法,使其使用相同的URL。这将起作用,因为常规的Index操作仅为GET,而您的"GetBy"操作仅为POST。因此,路由框架可以根据请求的方法来区分调用哪个。但是,由于这两个"GetBy"方法都只用于POST,因此这只适用于其中一个方法。

不过,我实际上建议你不要采取很多不同的行动,只需要有一个采用Report模型的Index的后版本,以及一些不同的参数。例如:

[HttpPost]
public ActionResult Index(Report fromPage, string getBy)
{
    if (getBy == "dateRange")
    {
        // do something
    }
    if (getBy == "specificDate")
    {
       // do soemthing else
    }
}

然后,您只需要在表单中为getBy传递一些值。最简单的方法可能是添加一个隐藏字段:

@Html.Hidden("getBy", "dateRange")

最新更新