zoukankan      html  css  js  c++  java
  • MVC实用集锦(1)

    最近的项目是用asp.net MVC开发的,所以希望从实际开发的角度,通过一些实例,帮助大家快速的开发asp.net MVC程序。
    1.创建控件,MVC中通过htmlHelper生成HTML标签。

    1 <%= Html.TextBox("UserName")%>
    2 <%= Html.TextBox("UserName","Coolin")%>
    3 <%= Html.TextBox("UserName","Coolin",
    new { @class = "className",disabled = true })%>

    最后一项htmlAttributes,可以设置样式等属性。

    2.RegisterRoutes带来了什么变化。通过VS创建一个MVC应用程序,会在Global.asax中看到下面的代码(我添加了第一条)

    复制代码
    1 routes.MapRoute(
    2 "Account",
    3 "Account/List/{type}",
    4 new { controller = "Account", action = "List" }
    5 );
    6
    7 routes.MapRoute(
    8 "Default",
    9 "{controller}/{action}/{id}",
    10 new { controller = "Home", action = "Index", id = "" }
    11 );
    复制代码

    现在看一下它带来的变化,假设view有如下代码

    1 <%= Html.ActionLink("男性", "List", new { type = "Man" }) %>
    2 <%= Html.ActionLink("女性", "List", new { type = "Woman" }) %>

    1 <%= Url.RouteUrl("Account", new { controller = "Account", action = "List", type= "Man" }) %>
    2 <%= Url.RouteUrl("Account", new { controller = "Account", action = "List", type= "Woman" }) %>

    对应的Url应该是 localhost:XXXX/Account/List/Man 和 localhost:XXXX/Account/List/Woman
    当然也可以不在Global.asax中注册那条规则,对应的Url就会变成大家熟悉的 localhost:XXXX/Account/List?type=Man。
    顺便提一下我在开发中遇到过的一个问题,还以上面的例子为例,在程序的开发阶段,没有加入刚才那条规则,当我们在程序中加入了 sitemap(mvcsitemap),结果却是sitemap的路径永远不能指向Woman的路径,可能是sitemap不能通过 ?后面参数区分路径,后来加入了这条规则,url中去掉参数,问题解决了。

    3.ajax异步请求controller
    controller中有如下代码

    1 public ActionResult Delete(Guid id)
    2 {
    3 Delete(id);
    4 return Json(new { success = true });
    5 }

    view中代码如下

    复制代码
    1 $.getJSON(<%= Url.Action("Delete", "Account",new { id="xx-xx-xxx" }) %>,
    2 function(result) {
    3 if (result.success) {
    4 //通过脚本移除此行
    5 alert("删除成功!")
    6 }
    7 });
    复制代码

    4.扩展htmlHelper,方便在view中调用后台代码。
    步骤 1)创建静态类 HtmlHelperExtension。
    2)引入 System.Web.Mvc 。
    3)创建需要的方法,例如:

    1 public static string FirstExtension(this HtmlHelper htmlHelper)
    2 {
    3 return "FirstExtension";
    4 }

      4)在view中引入HtmlHelperExtension所在的命名空间(一定不要忘,我忘了很多次)
      5)在view中使用,例如 <%= Html.FirstExtension() %>
  • 相关阅读:
    golang删除数组某个元素
    golang用通道实现信号量,控制并发个数
    什么是ScaleIO中的forwards rebuild和backwards rebuild?
    SQL Server中的database checkpoint
    如何将thick provision lazy zeroed的VMDK文件转换为thick provision eager zeroed?
    LoadTestAgentResultsLateException in VS2010
    SQL Server Instance无法启动了, 因为TempDB所在的分区没有了, 怎么办?
    VMware vCenter中, 如何辩认虚机上Raw Device Mapping过了的一块物理磁盘?
    SQL Server AlwaysOn Setup Step-By-Step Guide
    TPC-E在populate测试Database时需要注意的一些事项
  • 原文地址:https://www.cnblogs.com/glb79809-glb/p/14090389.html
Copyright © 2011-2022 走看看