C# 在MVC操作方法中创建超链接
我的控制器中有一个返回C# 在MVC操作方法中创建超链接,c#,.net,asp.net,asp.net-mvc,linq,C#,.net,Asp.net,Asp.net Mvc,Linq,我的控制器中有一个返回JsonResult的操作方法: public JsonResult GetDetails() { var rows = //Linq-To-SQL //Linq-To-Entities var lifts = (from r in rows group r by new { r.LiftID, r.LiftDate } into g
JsonResult
的操作方法:
public JsonResult GetDetails()
{
var rows = //Linq-To-SQL
//Linq-To-Entities
var lifts = (from r in rows
group r by new { r.LiftID, r.LiftDate } into g
select new
{
ID = g.Key.LiftID,
Date = g.Key.LiftDate.ToShortDateString(),
Driver = g.Where(x => x.IsDriver)
.Select(x => x.p).Single().Name,
Passengers = g.Where(x => !x.IsDriver)
.Select(x => x.p.Name)
.Aggregate((x, y) => x + ", " + y)
}).ToList();
return Json(lifts);
}
我在jQuery脚本中使用结果来编写一个表
数据如下所示:
身份证|日期|司机|乘客
1 | 20/06/2010 |大卫·尼尔|约翰·史密斯,保罗·琼斯
等等
我希望名称是指向路径Person\{id}
的超链接,即
。p
属性对应于一个Person
对象,该对象同时包含Name
和ID
我不想手动构造URL。如何使用MVC路由引擎将对象构造为包含名称的超链接?这相当简单
只需使用Url.Action(“actionName”,“controllerName”,params)
它将使用路由引擎创建一个字符串,因此如果您首先更改路由,您的代码将保持正常工作,我认为您的
模型
或Linq To SQL
或Linq To Entities
查询中存在错误。因为您没有个人的ID
(司机和乘客),如果您想要与该个人的ID链接,您肯定需要它。我认为你需要将你的电梯与你的人分开,并拥有两个独立的实体(当然由其Id链接)
其次,需要将人员的ID从控制器传递到视图
class Lift
{
public int LiftID { get; set; }
public DateTime LiftDate { get; set; }
public IEnumerable<Person> p { get; set; }
}
class Person
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsDriver { get; set; }
}
public JsonResult GetDetails()
{
var rows = new Lift[] { //Linq-To-SQL and Linq-To-Entities replaced by an example
new Lift{LiftID = 1, LiftDate= DateTime.Now, p = new Person[] {
new Person{IsDriver = true, Id = 1, Name = "David Neale"},
new Person{IsDriver = false, Id = 2, Name = "John Smith"},
new Person{IsDriver = false, Id = 3, Name = "Paul Jones"}
}},
new Lift{LiftID = 2, LiftDate= DateTime.Now, p = p = new Person[] {
new Person{IsDriver = true, Id = 4, Name = "Daniel Faraday"},
new Person{IsDriver = false, Id = 2, Name = "John Smith"}
}}
};
var lifts = (from r in rows
select new
{
ID = r.LiftID,
Date = r.LiftDate.ToShortDateString(),
Driver = r.p.Where(x => x.IsDriver)
.Select(x => x.Name).Single(),
Passengers = r.p.Where(x => !x.IsDriver)
.Select(x => x.Name)
.Aggregate((x, y) => x + ", " + y)
}).ToList();
return Json(lifts);
}
如果事先知道动作和控制器,可以执行以下操作:
var baseURL=''代码>
然后从jQuery手动构建链接,href设置为baseUrl+“/”+personId
正如我所说,p表示类型为Person
的对象。该类型确实包含一个ID
属性,我只是没有费心向您展示该类型的结构。ActionLink
HTML助手无法工作,因为客户端的jQuery正在填充该数据。发回的数据需要是有效的HTML。json数据是通过ajax调用返回的,因此我不能使用服务器标记。您不能只在(f.ex in(document).ready(…)
)上全局声明它,然后从异步响应中引用它?如果我误解了您的问题,查看一些视图可能会有所帮助。
<%= Html.ActionLink("Person", "Index", new { id = p.Id })%>