• 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() %>
  • 相关阅读:
    JAVA基础知识
    php中数据库服务器连接类库文件的编写
    面向对象三大特征之 封装
    composer 报错处理
    【Linux】ssh免密登录
    【天天数据结构和算法】PHP中trie数据结构的使用场景和代码实例
    【天天数据结构和算法】PHP实现二叉搜索树
    【天天数据结构和算法】PHP实现二分查找的两种方法
    【Linux】CentOS 7下yum成功安装 MySQL 5.7
    【实例】除法转移位运算
  • 原文地址:https://www.cnblogs.com/glb79809-glb/p/14090389.html
Copyright © 2020-2023  润新知