Reputation: 3
First of all, I need to know how I can get a row from the database by some how using the URL{id} as the value that I need, to query my database for the TripId. Once I have that I then need to pass it to the view.
In my controller I was looking for the tripid value '1' just to see if I could get that displaying on my view. but i expect that is where I would have a more complex query
Any help is greatly appreciated!
This is the controller
public class TripsController : Controller
{
private ApplicationDbContext _db = new ApplicationDbContext();
ActionResult View(int id)
{
using (ApplicationDbContext _db = new ApplicationDbContext())
{
var trip = (from Trips in _db.Trips
where Trips.TripId.Equals('1')
select Trips.TripId);
if (trip == null)
{
return HttpNotFound();
} else
{
/// Code to display page?
}
}
}
}
This is my model
public class Trips
{
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int TripId { get; set; }
public string Country { get; set; }
public string City { get; set; }
public string Description { get; set; }
public int Price { get; set; }
public DateTime Date { get; set; }
public int CoachId { get; set; }
}
}
And lastly the view..
@model _MVCCoachTravelling.Models.Trips
@{
ViewBag.Title = "View";
}
<div class="main-container">
<div class="row">
<img class="img-responsive" src="http://placehold.it/800x300" alt="">
<div class="caption-full">
<h4 class="pull-right">£@Html.DisplayFor(model => model.Price)</h4>
<h4>
@Html.DisplayFor(model => model.City)
</h4>
<p>@Html.DisplayFor(model => model.Description)</p>
</div>
Upvotes: 0
Views: 77
Reputation: 14250
If your query fails it is because you are comparing a char to an int
where Trips.TripId.Equals('1')
You should instead compare
where Trips.TripId == 1
Once you get your trip it is now return View(trip)
.
public ActionResult ViewTrip(int id)
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
var query = from t in db.Trips
where t.TripId == id
select t;
var trip = query.FirstOrDefault();
if (trip == null) { /* fail */ }
return View(trip);
}
}
Upvotes: 2
Reputation: 3281
You can simply try:
ActionResult View(int id)
{
using (ApplicationDbContext _db = new ApplicationDbContext())
{
var trip = (from Trips in _db.Trips where Trips.TripId.Equals('1') select Trips.TripId);
if (trip == null)
return HttpNotFound();
return View()
}
}
Provided your view is correctly mapped to a controller and model.
Upvotes: 0