Search code examples
asp.net-mvc-5

Access data of one view on another view in ASP.NET MVC5


I have created a controller with following code. **I am not using any model in this example.

public ActionResult PersonalDetails()
{
    return View();
}

[HttpPost]
public ActionResult Thanks(FormCollection formcol)
{
    return View();
}

Also a view is added for PersonalDetails action with following markup.

@{
    ViewBag.Title = "PersonalDetails";
}

<h2>PersonalDetails</h2>

@{
    ViewBag.Title = "PersonalDetails";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>PersonalDetails</h2>

@using (Html.BeginForm("Thanks", "DemoForms", FormMethod.Post))
{    
    @Html.ValidationSummary()

    <p>
        Your Name : @Html.TextBox("FirstName")
    </p>
    <br />
    <p>
        Your Name : @Html.TextBox("LastName")
    </p>
    <p> Your Phone : @Html.TextBox("Phone")</p>
    <p> @Html.RadioButton("Gender", "Male", true) Male</p>
    <br />
    <p>@Html.RadioButton("Gender", "Female", false) Female </p>
    <p> @Html.CheckBox("Reading", true) Reading</p><br />
    <p> @Html.CheckBox("Cooking", false) Cooking</p><br />
    <p> @Html.CheckBox("Cooking", false) Painting</p><br />

    <p>
        Would you like to participate in Survey?
        @Html.DropDownList("ddlResponse", new[]
    {
         new SelectListItem() {Text="Yes", Value="Yes"},
         new SelectListItem() {Text="No", Value="No"}
    }, "Choose an Option")

    </p>
    <input type="submit" value="Submit Invite" />
}

When user enter the information in above view and click on submit button, it will redirect to Thanks action. I want to create a Thanks view that will show this information. Please let me know how I can show/access the information on Thanks view.

Thank you in advance.


Solution

  • A typical way to do this is to simply send the data to the new view on the server. There are a lot of different patterns. For model binding, do something like this:

    [HttpPost]
    public ActionResult Thanks(FormCollection formcol)
    {
        ThanksViewModel model=new ThanksViewModel();
    
        //add the data to the model
    
        return View(model); //return the model with the view 
    }
    

    If you're not using the model-binding functionality in your view pages, you can always pass data using the ViewBag:

    [HttpPost]
    public ActionResult Thanks(FormCollection formcol)
    {
        ViewBag.ThanksData="data"; //add data as properties of ViewBag
    
        return View();
    }
    

    The ViewBag is just a built-in dynamic type that you can store any data on. You can then render this data in the view using the standard razor syntax. Eg in the razor page:

    @{
        ViewBag.Title = "PersonalDetails";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h2>PersonalDetails</h2>
    <p>@ViewBag.ThanksData</p>