ASP.NET MVC5 学习笔记

URL参数方式

  • /HelloWorld/Welcome?name=Scott&numtimes=4)
  • /HelloWorld/Welcome/3?name=Scott
public string Welcome(string name, int numTimes = 1)
{
    return HttpUtility.HtmlEncode("Hello " + name + ", NumTimes is: " + numTimes);
}
  • HelloWorld/Welcome/Scott/3
    这个需要自定义路由支持此种方法
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

    routes.MapRoute(
       name: "Hello",
       url: "{controller}/{action}/{name}/{id}"
   );
}
  • HttpPost特性修饰(代码中黄色背景标注),这个特性指定只有POST请求才能调用这个重载的Edit方法。我们可以为第一个Edit方法添加HttpGet特性,但这不是必须的,因为它是默认值(我们将未标记的方法认定为HttpGet方法)
  • 控制器方法中的ValidateAntiForgeryToken 特性,这个特性用来阻止伪造的请求,它和视图中的 @Html.AntiForgeryToken() 是成对出现的。
//
// POST: /Movies/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Movie movie)
{
    if (ModelState.IsValid)
    {
        db.Entry(movie).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(movie);
}
@model MvcMovie.Models.Movie

@{
    ViewBag.Title = "Edit";
}

Edit

@using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true)
class="form-horizontal"> Movie @Html.HiddenFor(model => model.ID)
class="control-group"> @Html.LabelFor(model => model.Title, new { @class = "control-label" })
class="controls"> @Html.EditorFor(model => model.Title) @Html.ValidationMessageFor(model => model.Title, null, new { @class = "help-inline" })

你可能感兴趣的:(ASP.NET,MVC)