public static class HtmlHelpers
{
public static string Truncate(this HtmlHelper helper, string inputString, int length)
{
string tempString = string.Empty;
for (int i = 0, tempIndex = 0; i < inputString.Length; ++i, ++tempIndex)
{
if (System.Text.Encoding.UTF8.GetBytes(new char[] { inputString[i] }).Length > 1)
{
++tempIndex;
}
if (tempIndex >= length)
{
tempString += "...";
break;
}
tempString += inputString[i];
}
return tempString;
}
}
分类目录归档:.NET MVC
Razor@@ @:
@@code
输出@code
@:code
输出code
.net mvc中@ 和response.write的区别 Difference between @ and response.write
Razor会自动的将输出进行Html编码,可以帮助防止跨站点攻击。
如果有人将恶意脚本放进数据库,而Razor没有进行Html编码的话,浏览器就会看到一个<script>标签和可执行的JavaScript。
ActionResults action returns
| Name | Framework Behavior | Producing Method |
|---|---|---|
| ContentResult | Returns a string literal | Content |
| EmptyResult | No response | |
| FileContentResult FilePathResult FileStreamResult |
Return the contents of a file | File |
| HttpUnauthorizedResult | Returns an HTTP 403 status | |
| JavaScriptResult | Returns a script to execute | JavaScript |
| JsonResult | Returns a data in JSON format | Json |
| RedirectResult | Redirects the client to a new URL | Redirect |
| RedirectToRouteResult | Redirect to another action, or another controller’s action |
RedirectToRoute RedirectToAction |
| ViewResult PartialViewResult |
Response is the responsibility of a view engine |
View/PartialView |
Html.BeginForm add class attribute
@Html.BeginForm("DoSearch", "Search", FormMethod.Post, new { @class = "myclass"})
.net mvc display image from file
controller:
public ActionResult Image(string id)
{
var dir = Server.MapPath("/Images");
var path = Path.Combine(dir, id + ".jpg");
return base.File(path, "image/jpeg");
}
view:
<img src="@Url.Action("Image", new { id= Model.Guid })" alt="@Model.Name" width="300" >
Using the ASP.NET MVC 3 Logon returnUrl Parameter
razor:
@{
ViewBag.Title = "登陆";
Layout = "~/Views/Shared/_LoginLayout.cshtml";
string retUrl = "";
if (Request["ReturnUrl"] != null)
{
retUrl = ViewContext.HttpContext.Request["ReturnUrl"];
}
}
@using (Html.BeginForm("Logon", "Account", new { model = this.Model, ReturnUrl = retUrl }))
{
//form
}
controller:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string ReturnUrl)
{
ViewBag.UserLogOut = true;
if (!ModelState.IsValid)
return View("Logon");
if (ModelState.IsValid)
{
try
{
//login
}
catch (Exception e)
{
ModelState.AddModelError("", e.Message);
return View(model);
}
}
if (!string.IsNullOrEmpty(ReturnUrl))
return Redirect(ReturnUrl);//return
return RedirectToAction("Index", "Product");
}
UserSessionAuthorizeAttribute:
public class UserSessionAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if(//check session)
{
filterContext.Result = new RedirectToRouteResult(
new System.Web.Routing.RouteValueDictionary
{
{ "controller", "Account" },
{ "action", "LogOn" },
{ "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
});
}
}
}
mvc3 ajax refresh partial page
$.get('@(Url.Action("HeaderLinks", "Common" ))', function (data) {
$('#header-links-wrapper').html(data);
});
MVC3-Razor输出Html
输出HTML代码(包含标签):直接输出,
string html = "文本";
@html
输出HTML内容(不包含标签):有两种方法,
第一种:
IHtmlString html=new HtmlString("文本");
@html ;
第二种:
string html = "文本";
@Html.Raw(html);
.net mvc 中使用ActionFilterAttribute过滤器
过滤器是mvc中常用的
在.net mvc 中直接继承和实现ActionFilterAttribute类就可以了
很简单
下面贴出一个例子
过滤器:
public class UseStopwatchAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
filterContext.Controller.ViewData["stopWatch"] = stopWatch;
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
Stopwatch stopWatch = (Stopwatch)filterContext.Controller.ViewData["stopWatch"];
stopWatch.Stop();
Random r = new Random();
filterContext.Controller.ViewData["elapsedTime"] = stopWatch.ElapsedMilliseconds
+ " milliseconds - Rand " + r.Next(1000).ToString();
}
}
这的话这个过滤器就写好了
在使用的时候只要在controller上写上就行了
[UseStopwatch]
public class ProductsController : Controller
{
//
// GET: /Store/Products/
public ActionResult List()
{
return View();
}
public ActionResult Details()
{
return View();
}
public ActionResult AddReview()
{
return View();
}
}