ASP.Net Mvc 3 Url.Action method uses parameter values from previous request

混江龙づ霸主 提交于 2019-11-30 18:52:48

Weird, can't seem to reproduce the problem:

public class HomeController : Controller
{
    public ActionResult Index(string id)
    {
        return View();
    }

    public ActionResult About(string id)
    {
        return View();
    }
}

and inside Index.cshtml:

@Url.Action("About", "Home")

Now when I request /home/index/123 the url helper generates /home/about as expected. No ghost parameters. So how does your scenario differs?


UPDATE:

Now that you have clarified your scenario it seems that you have the following:

public class HomeController : Controller
{
    public ActionResult Index(string id)
    {
        return View();
    }
}

and inside Index.cshtml you are trying to use:

@Url.Action("Index", "Home")

If you request /home/index/123 this generates /home/index/123 instead of the expected /home/index (or simply / taken into account default values).

This behavior is by design. If you want to change it you will have to write your own helper which ignores the current route data. Here's how it might look:

@UrlHelper.GenerateUrl(
    "Default", 
    "index", 
    "home", 
    null, 
    Url.RouteCollection, 
    // That's the important part and it is where we kill the current RouteData
    new RequestContext(Html.ViewContext.HttpContext, new RouteData()), 
    false
)

This will generate the proper url you were expecting. Of course this is ugly. I would recommend you encapsulating it into a reusable helper.

WEFX

Use Darin's answer from this similar question.

@Url.Action("Edit","Student", new { ID = "" })

Use ActionLink overload that uses parameters and supply null

You could register custom route for this action for example:

routes.MapRoute("Domain_EditStudentDefault",
            "student/edit",
            new { 
                controller = MVC.Student.Name, 
                action = MVC.Student.ActionNames.Edit,
                ID = UrlParameter.Optional
            },
            new object(),
            new[] { "MySolution.Web.Controllers" }
        );

you then could use url.RouteUrl("Domain_EditStudentDefault") url RouteUrl helper override with only routeName parameter which generates url without parameters.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!