简体   繁体   中英

Error with a RouteValue string that has the same name as an Action Controller

I originally had the following code inside a view:

return RedirectToAction("Error", new { error = "User Already Exists" });

This caused the View not found error:

在此处输入图片说明

Changing the code to the following works fine:

return RedirectToAction("Error", new { errorid = "User Already Exists" });

Considering both are just string names, I am sure I am calling the same overload in both cases, but, I just can't understand what is wrong here / why it thinks I need a different view.

What have I done wrong?


@SLaks' Request -

    public ActionResult Error(string errorid)
    {
        ViewBag.error = errorid;

        return View();
    }

(before, errorid was simply just error)

What most likely happened is your Error method was constructed like

public ActionResult Error(string errorid) {
    ViewBag.error = errorid;

    return View(errorid);
}

instead of you using the ViewBag . This will cause the exact error that occurred. You probably had your model as @model string . The reason this would fail and cause that error is because the signature for View(string) assumes you're passing in which view (and not the model) you want to see. In this case to fix it you'll want to do something like return View("Error", errorid); where the second parameter is your model.

ASP.Net MVC matches routes to actions using parameter names.

Therefore, the parameter names in the route / URL must exactly match the action's parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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