bkhosh2 bkhosh2 - 11 months ago 63
C# Question

RequestContext.RouteData and Request.UrlReferrer info is lost on FormMethod.Post

I am trying to post a form with one of the variables being the Action of the previous URL, however whenever I POST it, the variable becomes null. How can I persist that info at least until it reaches the POST Action?

I've tried using both

to get the Action.

In my View I'm trying to POST a file, Action name, and an id:

Html.BeginForm("Edit", "Expenses", FormMethod.Post, new { enctype = "multipart/form-data", actionName = actionName, id = idInt })

If I keep it the way it is, the Action name is null, but if I remove the FormMethod.Post portion from the BeginForm method, the Action name is posted successfully and the file is null.

Answer Source

You are using the Html.BeginForm helper method incorrectly! You mixed route values and html attributes to a single object !

Your current call matches the below overload

public static MvcForm BeginForm(
    this HtmlHelper htmlHelper,
    string actionName,
    string controllerName,
    FormMethod method,
    IDictionary<string, object> htmlAttributes

The last parameter is the htmlAttributes. So with your code, it will generate the form tag markup like this

<form action="/Expenses/Edit" actionname="someActionName" enctype="multipart/form-data"
                                                                     id="22" method="post">


You can see that Id and action became 2 attributes of the form !

Try this overload where you can specify both route values and htmlAttributes

@using (Html.BeginForm("AddToCart", "Home",  new {  actionName = "Edit", id = 34 },
                                 FormMethod.Post,new { enctype = "multipart/form-data", }))
        <input type="submit"/>

which will generate the correct form action attribute value using the route values you provided.