首页 > 代码库 > mvc area区域和异步表单,bootstrap简单实例

mvc area区域和异步表单,bootstrap简单实例

码农最怕眼高手低

今天来练习mvc Area技术和bootstrap以及异步表单的C#代码实现。

1.area区域架构对于建立复杂业务逻辑很有帮助,由  AreaRegistration.RegisterAllAreas()方法遍历路由表,获得所有注册的路由。参见

建立类库Common,下设一个文件夹BookStore

在其中建立model和controller。(注意引用System.Web.Mvc这个dll)

项目结构如图:

其中book.cs为model模型

namespace Common.BookStore{   public  class Book    {       public string bookName { get; set; }       public double price { get; set; }       public string bookType { get; set; }       public int num { get; set; }    }}

 

注意controller中不要忘了继承Controller

namespace Common.BookStore{   public  class BookCurdController:Controller    {
    //添加页面
public ActionResult BookAdd() { return View(); }
    //模拟添加操作页面
public ActionResult _BookAdd(Book bookModel) { bookModel.num += 1; return View(bookModel); } }}

 

2.建立一个基本mvc程序,我用的mvc4,在根目录下建立Areas文件夹,然后右键-添加-区域,输入我们的BookStore

这样我们添加了一个区域,删除其中的controller和model文件夹。

接着对生成的BookStoreAreaRegistration进行修改

    public class BookStoreAreaRegistration : AreaRegistration    {        public override string AreaName        {            get            {
         //此为区域的名称,与我们的区域文件夹同名
return "BookStore"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "BookStore_default", "BookStore/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional }, //命名空间不可少 new string[] { "Common.BookStore" } ); } }

生成Common类库,在web站点添加对其的引用。

3.现在进行页面部分的制作,我们先添加bootstrap文件,我从ExtJs源码中把bootstrap几个文件扣了出来,添加到web程序中,就像这样

接着,我们添加页面上的引用(或者你把它们放到一个局部视图或者模板视图中也行)

    <link href=http://www.mamicode.com/"@Url.Content("~/Content/bootstrap/css/bootstrap.css")" rel="stylesheet" type="text/css" />    <script type="text/javascript" src=http://www.mamicode.com/"@Url.Content("~/Scripts/jquery-1.7.1.js")"></script>    <script type="text/javascript" src=http://www.mamicode.com/"@Url.Content("~/Scripts/jquery.validate.min.js")"></script>    <script type="text/javascript" src=http://www.mamicode.com/"@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")"></script>    <script type="text/javascript" src=http://www.mamicode.com/"@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"></script>      <script type="text/javascript" src=http://www.mamicode.com/"@Url.Content("~/Content/bootstrap/js/jqBootstrapValidation.js")"></script>  

 

套用一个bootstrap框架

<div class="container-fluid" style="margin-top:30px;">         <div class="row">                    <div class="col-xs-12">                        <div class="form-group">                            <label class="control-label col-xs-4" for="bookName">书名:</label>                            <div class=" col-xs-4">                                <input id="bookName" class="form-control" type="text" name="bookName"   value=http://www.mamicode.com/"" />                            </div>                        </div>                    </div>
    </div></div>

 

在这里说明一下,bootstrap依循网格系统,分为12列,最基础的属性由less构建(所以想改造它,可以直接修改less),其中.col-xs-* 是针对小尺寸设备(<768px)的样式。具体参考

http://www.w3cschool.cc/bootstrap/bootstrap-grid-system.html

在设置完样式之后,我们引入异步代码

  @using (Ajax.BeginForm(
          //指定action,controller
          "_BookAdd", "BookCurd", null, new AjaxOptions() {
           //更新还是替换 InsertionMode
= InsertionMode.Replace, HttpMethod = "POST", //标记要更新的div,页面部分由jquery.validate.unobtrusive.js完成 UpdateTargetId = "showMsg", //提交成功 OnSuccess = "OnSuccess", //提交失败 OnFailure = "OnFailure", //完成 OnComplete = "OnComplete" }, //这个参数设置form表单的属性 htmlAttributes: new { name = "nbform", id = "nbform", @class = "form-horizontal" })) { ....... }

 

最后页面如下

@{    Layout = null;}<!DOCTYPE html><html><head>    <meta name="viewport" content="width=device-width" />    <title>图书添加</title>    <link href=http://www.mamicode.com/"@Url.Content("~/Content/bootstrap/css/bootstrap.css")" rel="stylesheet" type="text/css" />    <script type="text/javascript" src=http://www.mamicode.com/"@Url.Content("~/Scripts/jquery-1.7.1.js")"></script>    <script type="text/javascript" src=http://www.mamicode.com/"@Url.Content("~/Scripts/jquery.validate.min.js")"></script>    <script type="text/javascript" src=http://www.mamicode.com/"@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")"></script>    <script type="text/javascript" src=http://www.mamicode.com/"@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"></script>      <script type="text/javascript" src=http://www.mamicode.com/"@Url.Content("~/Content/bootstrap/js/jqBootstrapValidation.js")"></script>      <script type="text/javascript">        $(function () {            $.AddCheckBoxRadioLinster("nbform");        });        function OnSuccess() {            alert("提交成功");        }        function OnFailure() {            alert("提交失败");        }        function OnComplete() {                 }    </script></head><body>    <div class="container-fluid" style="margin-top:30px;">          @using (Ajax.BeginForm("_BookAdd", "BookCurd", null,                new AjaxOptions()                {                    InsertionMode = InsertionMode.Replace,                    HttpMethod = "POST",                    UpdateTargetId = "showMsg",                    OnSuccess = "OnSuccess",                    OnFailure = "OnFailure",                    OnComplete = "OnComplete"                },htmlAttributes: new { name = "nbform", id = "nbform", @class = "form-horizontal" }))          {                        <div class="row">                    <div class="col-xs-12">                        <div class="form-group">                            <label class="control-label col-xs-4" for="bookName">书名:</label>                            <div class=" col-xs-4">                                <input id="bookName" class="form-control" type="text" name="bookName"   value=http://www.mamicode.com/"" />                            </div>                        </div>                    </div>                </div>              <div class="row">                    <div class="col-xs-12">                        <div class="form-group">                            <label class="control-label col-xs-4" for="price">价格:</label>                            <div class="col-xs-4">                                <input id="price" class="form-control" type="text" name="price" maxlength="16" minlength="1"  data-validation-minlength-message="价格最少1位!"  data-validation-required-message="不能为空!" required />                            </div>                        </div>                    </div>                </div>               <div class="row">                    <div class="col-xs-12">                        <div class="form-group">                            <label class="control-label col-xs-4" for="bookType">种类:</label>                            <div class="col-xs-4">                                                            <label class="checkbox-inline" >                                <input type="checkbox" id="bookTypeCheckbox" name="bookTypeCheckbox" value=http://www.mamicode.com/"电子书"/>电子书                                     </label>                                 <label class="checkbox-inline" >                                <input type="checkbox"  name="bookTypeCheckbox" value=http://www.mamicode.com/"印刷版"/>印刷版                                     </label>                                <input type="hidden" id="bookType" name="bookType" />                                                          </div>                        </div>                    </div>                </div>                           <div class="row">                    <div class="col-xs-12">                        <div class="form-group">                            <label class="control-label col-xs-4" for="num">数量:</label>                            <div class="col-xs-4">                                <input id="num" class="form-control" type="text" name="num" maxlength="16" minlength="0"    data-validation-required-message="不能为空!" required />                            </div>                        </div>                    </div>                </div>              <div class="row" >                   <div class="col-xs-3 col-md-offset-4">                       <button type="submit" class="btn btn=default">提 交</button>                   </div>              </div>             }</div>    <div class="container" id="showMsg">    </div></body></html>
View Code

 

 效果如图:

 

这里还要说明一下,$.AddCheckBoxRadioLinster("nbform");这个是jqBootstrapValidation.js中的函数很好用。我们看一下他的内部实现

  $("#" + formId + " input[type=‘checkbox‘],input[type=‘radio‘]").each(                function () {                    $(this).change(function() {                        var name = $(this).attr("name");                        var value = http://www.mamicode.com/"";                        $("#" + formId + " input[name=‘" + name + "‘]:checked").each(function() {                            value = value + ";" + $(this).val();                        });                        var length = $(this).attr("type") == "radio" ? 5 : 8;                        if (value =http://www.mamicode.com/= "") {                            $("#" + $(this).attr("name").substr(0, $(this).attr("name").length - length)).val("-1");                        } else {                            $(this).parents(".form-group").first().removeClass("error");                            $("#" + $(this).attr("name").substr(0, $(this).attr("name").length - length)).attr("value",length == 5 ? value.substr(1, length) : value + ";");                        }                    });                }            );

 

以字符串拼接的方式来约束字段和处理,它不但可以动态绑定checkbox,radio还可以绑定select下拉框。。。。。。

关于jqBootstrapValidation类似于maxlength 来约束输入的更多用法,参见:

http://reactiveraven.github.io/jqBootstrapValidation/