Reputation: 598
I'm trying to compare two cars details in the same View page. I do not want to use ViewBag method to send my data to view since I heard from many it's not a recommended way of passing data.
I couldn't find any information in this matter. I've tried to send both cars' details in one query but that will be very complicated and I was not successful to differentiate the first from second car in my View.
Here's the shortened form of my view:
@model IEnumerable<Cars.Models.Car>
@using (Html.BeginForm("Comparison", "Home", FormMethod.Post,
new { id = "ComparisonFormID" }))
{
<table>
<tr>
<td>
<p>First car:</p>
@Html.DropDownList("carMake","All Makes")
</td>
<td>
<p>Second car:</p>
@Html.DropDownList("carMake2", "All Makes")
<button type="submit" name="submit" value="search" id="CompareID">Compare</button>
</td>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
<label>Make:</label>
</td>
<td>
<p>@Html.DisplayFor(modelItem => item.Make)</p> @*First car's information*@
</td>
<td>
<p>@Html.DisplayFor(modelItem => item.Make)</p> @*Second car's information*@
</td>
</tr>
}
</table>
}
Shortened version of my model class:
public class Car
{
public int ID { get; set; }
public String Make { get; set; }
}
and finally my controller:
public ActionResult Comparison(String carMake, String carMake2)
{
var makeLstBase = new List<String>();
var makeQryBase = from m in db.Car
orderby m.Make
select m.Make;
makeLstBase.AddRange(makeQryBase.Distinct());
ViewBag.carMake = new SelectList(makeLstBase);
ViewBag.carMake2 = new SelectList(makeLstBase);
var cars = from m in db.Car
orderby m.Make
where m.Make == carMake || m.Make == carMake2
select m;
return View(cars);
}
Please notice that I'm using ViewBag for filling the dropdownlist when the page is loading. Now I'm trying to show the two different car brands in two different columns, in order to compare cars with each other in details.
My question: What is the best way to take two queries from the same model class and send it to the view?
Thank you.
Upvotes: 0
Views: 276
Reputation: 16032
From your View i guess you want to display a list of comparisons? Just create a class for one row in your table:
public class CarComparisonViewModel
{
Car Car1 { get; set; }
Car Car2 { get; set; }
}
In your view you take a list of those comparisons:
@model IEnumerable<CarComparisonViewModel>
@foreach (var item in Model)
{
<tr>
<td>
<label>Make:</label>
</td>
<td>
<p>@Html.DisplayFor(m => item.Car1.Make)</p>
</td>
<td>
<p>@Html.DisplayFor(m => item.Car2.Make)</p>
</td>
</tr>
Im not sure, how you want to query your cars, so i leave the action part out until you provide more information on that.
Upvotes: 2