Reputation: 2056
Alright so i want to pass data from the view back to Post Method in the controller.
The View :
@model IEnumerable< MvcMobile.Models.Trips>
<p>Time : @ViewBag.titi</p>
<p>ID :@ViewBag.iid </p>
<p>From : @ViewBag.From</p>
<p>To :@ViewBag.To </p>
Avaibliabe Trips :
@foreach (var item in Model)
{
if ( item.Time==ViewBag.titi)
{
<p>@item.TripID</p>
}
}
My HttpGet Method in the controller :
[HttpGet]
public ActionResult Book2(MvcMobile.Models.TicketsBooked tik)
{
ViewBag.titi = tik.Time;
ViewBag.iid = tik.TicketID;
ViewBag.from = tik.From;
ViewBag.To = tik.To;
var TripsList = db.Trips.ToList();
return View(TripsList);
}
In This case i cant use a dynamic object to pass variable since the model is IEnumerable
i want to pass one or two textBoxes back to the controller, how can i do that ?
an alternative question would be how can i do the same functionality in the view without making the model IEnumberable ?
and thanks alot.
Upvotes: 1
Views: 3567
Reputation: 3689
You should read up on using view models. Basically it's best practice to only pass relevant data to the view. So instead on passing a model of IEnumerable you would have a view model with a property of IEnumerable plus the extra properties you want to post back to your controller.
So for example:
public class ViewModel
{
public IEnumerable<MvcMobile.Models.Trips> Trips { get; set; }
public string ExtraValue { get; set; }
}
and your view would be:
@foreach(var trip in Model.Trips)
{
<p>Do stuff</p>
}
@Html.TextBoxFor(m => m.ExtraValue)
Your post method would then accept a ViewModel.
[HttpPost]
public ActionResult Book2(ViewModel viewModel)
{
}
You can read up more on view models here or by searching Google / SO. There are many, many examples.
Upvotes: 1