blisher
blisher

Reputation: 75

Passing data between controller and view - ASP.NET MVC 4

I am making a simple survey, for learning basics of ASP.NET MVC 4. Here's my code

        [HttpGet]
        public ActionResult Index()
        {
            UserAndTableViewmodel Viewmodel = new UserAndTableViewmodel();
            Viewmodel.T = Deserialize();
            Viewmodel.U = new User();

            for (int i = 0; i < Viewmodel.T.Questions.Count(); i++)
            {
                Viewmodel.U.UserChoices.Add(new Choice(Viewmodel.T.Questions[i].Choices[0].Value));
            }

            return View(Viewmodel);
        }

        [HttpPost]
        public ActionResult Index(UserAndTableViewmodel Viewmodel)
        {
            // Viewmodel.T = Deserialize();

            if (ModelState.IsValid)
            {
                return View("Thanks", Viewmodel);
            }
            else
            {
                return View(Viewmodel);
            }
        }

The XML code is as followed:

<Table>
  <Question Content="Question one">
    <Choice Value="Answer 1" />
    <Choice Value="Answer 2" />
  </Question>
  <Question Content="Question two">
    (...)
  </Question>
</Table>

I'm passing deserialised data to "Index" view, where user can choose his answers. Then data is post to [HttpPost] and i want it to render a view, where each question with its answer is written, but problem occurs - Viewmodel.T is equal to null. What am I supposed to do, that I shouldn't deserialize it again?

Upvotes: 2

Views: 2415

Answers (2)

Aage
Aage

Reputation: 6252

You could render a hidden field for your property, like so:

View:

@model Namespace.UserAndTableViewmodel 

@using(Html.BeginForm()){
    @Html.HiddenFor(m => m.T)
    ...
}

Now you should have a value in your HttpPost method. Basically, if a value isn't rendered in your view, it won't get posted to the HttpPost method. Your view model doesn't hold on to values between roundtrips between the view and the controller. This is why you also need to repopulate a view model in your HttpPost before returning it to the view again. It doesn't have the values you've set in the HttpGet.

(Only use hidden fields for data that doesn't need to be secured though. You could also use @Html.TextBoxFor or @Html.LabelFor)

Upvotes: 2

Hope
Hope

Reputation: 1292

You don't want to do any serialize or deserialise in MVC4. Just pass your data as a view model object, that will be available in your view.

Upvotes: 3

Related Questions