首先,我需要知道如何从数据库中获取一些如何使用URL {id}作为我需要的值来查询我的数据库中的TripId。一旦我有了,我就需要将它传递给视图。
在我的控制器中,我正在寻找三脚架价值' 1'只是为了看看我是否可以在我的视图中显示。但我希望这是我将有一个更复杂的查询
非常感谢任何帮助!
这是控制器
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?
}
}
}
}
这是我的模特
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; }
}
}
最后是观点..
@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>
答案 0 :(得分:2)
如果查询失败,那是因为您要将char与int进行比较
where Trips.TripId.Equals('1')
你应该比较
where Trips.TripId == 1
一旦您结束旅行,现在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);
}
}
答案 1 :(得分:0)
您可以尝试:
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()
}
}
如果您的视图已正确映射到控制器和模型。