ASP.NET MVC 3在cshtml文件中使用C#代码
我对ASP.NET MVC3有点陌生。 我有一个cshtml文件中的代码ASP.NET MVC 3在cshtml文件中使用C#代码,c#,asp.net-mvc-3,razor,C#,Asp.net Mvc 3,Razor,我对ASP.NET MVC3有点陌生。 我有一个cshtml文件中的代码 @grid.GetHtml( htmlAttributes: new { id = "grid" }, tableStyle: "grid", headerStyle: "header", rowStyle: "row", footerStyle: "footer", alternatingRowStyle: "altR
@grid.GetHtml(
htmlAttributes: new { id = "grid" },
tableStyle: "grid",
headerStyle: "header",
rowStyle: "row",
footerStyle: "footer",
alternatingRowStyle: "altRow",
columns: grid.Columns(
grid.Column(header: "", format: @<text><input name="Checked" type="checkbox" value="@item.Key" /></text>, style: "CheckboxColumn", canSort: true),
grid.Column("Name", "Name"),
grid.Column("Address", "Address"),
grid.Column("City", "City"),
grid.Column("PhoneNumber", "Phone Number"),
grid.Column("", format: (item) =>
{
if (item.ID.Length > 0)
{
//CODE GOES HERE
return Html.Raw(string.Format("<text><img src=\"{0}\" alt=\"Image\" class=\"ToolTip\" title=\"ID # {1} <br> \" /></text>", Url.Content("~/images/coupled.png"), @item.ID.ToString()));
}
else
{
return Html.Raw("<text></text>");
}
}),
))
最后使用Url.Content(URLOfPic)
那么如何在页面中使用C代码呢
我希望我是清楚的。
非常感谢你的帮助
PS:我希望它是一个C代码,而不是javascript或其他任何东西。
在普通的ASP.NET中,我只需要使用代码就可以了。但是在MVC3中,我不知道你是如何接近的,这不起作用吗
if (item.ID.Length > 0)
{
string URLOfPic;
if(item.ID > 1000)
{
URLOfPic="~/images/aaa.png";
} else {
URLOfPic="~/images/bbb.png";
}
return Html.Raw(string.Format("<text><img src=\"{0}\" alt=\"Image\" class=\"ToolTip\" title=\"ID # {1} <br> \" /></text>", Url.Content(URLOfPic), @item.ID.ToString()));
}
if(item.ID.Length>0)
{
一串字母;
如果(项目ID>1000)
{
URLOfPic=“~/images/aaa.png”;
}否则{
URLOfPic=“~/images/bbb.png”;
}
返回Html.Raw(string.Format(“\”/>”,Url.Content(URLOfPic),@item.ID.ToString());
}
作为Asp.net mvc的新手,让我给你一些建议,不要这样做!视图中的大多数代码都是for循环,所有此类逻辑都应该在操作中完成
基本上,获取数据并在操作中执行所有逻辑和格式设置,然后将其添加到视图模型中,然后将其传递到视图。另一方面,您将创建非常脆弱的代码块,直到运行时才会出错。修改项目类以添加图像类。在图像类中,您可以添加image.URL、image.Titleoller您可以根据项目的ID为其分配一个图像。这还允许您在单个代码点更轻松地修改图像URL,而不是在使用此逻辑的每个视图中进行修改。您是否尝试过编写该代码?如果这样做会发生什么?您是否收到错误?错误说明了什么?没有发生什么你认为应该发生什么?创建一个助手方法。
if (item.ID.Length > 0)
{
string URLOfPic;
if(item.ID > 1000)
{
URLOfPic="~/images/aaa.png";
} else {
URLOfPic="~/images/bbb.png";
}
return Html.Raw(string.Format("<text><img src=\"{0}\" alt=\"Image\" class=\"ToolTip\" title=\"ID # {1} <br> \" /></text>", Url.Content(URLOfPic), @item.ID.ToString()));
}