分类目录归档:.NET MVC

.Net mvc自定义字符串截取(考虑全角/半角)

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;
  }
}

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

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-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();
  }
}