user1770407
user1770407

Reputation: 35

ASP.Net MVC sending model to view without using URL

I am using the same model between 2 views, but when posting the model to the second view it puts all the previously entered data in the URL. Is it possible to send the populated model to the second view without posting the data in the URL?

Controller code:

    [HttpPost]
    public ActionResult ViewExample1(.Models.RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            return RedirectToAction("ViewExample2", model);
        }
        return View(model);
    }

    public ActionResult ViewExample2(Models.RegisterModel model)
    {
        return View(model);
    }

Second view code where I use HiddenFor to persist the data when this view is posted back:

<% using (Html.BeginForm(null, null, FormMethod.Post, new { id="ViewExample2"})) { %>
    <%: Html.HiddenFor(model => model.UserName)%>
<% } %>

Upvotes: 0

Views: 1019

Answers (2)

Sandro
Sandro

Reputation: 3160

When you redirect to an action with RedirectToAction(), you're doing that by GET. So the Framework passes your view model in the url to the action.

I'd suggest you to do this:

[HttpPost]
public ActionResult ViewExample1(Models.RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Do the work you want to do in the ViewExample2 action here!
        // ... and then return the ViewExample2 view
        return View("ViewExample2", model);
    }
    return View(model);
}

// This action is not needed anymore
/*public ActionResult ViewExample2(Models.RegisterModel model)
{
    return View(model);
}*/

Upvotes: 1

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

My guess is that you're using a form tag (rather than BeginForm) and you aren't specifying a method, so it defaults to using a GET rather than a POST.

Convert to using a BeginForm, or add the method.

Upvotes: 0

Related Questions