LCD- Project -Develope Records (一)

一、table的操作
1.1 DataTable 与dataTable在调用时是有区别的。一定要注意大小写
一般要用DataTable
1.2 DataTable的thead必须有否则下方无法动态绑定数据。
1.3 数据的绑定方法
1.3.1 Json的绑定方法:
思路:可先对表格进行DataTable规划;然后对Json进行遍历, 以t.row.add([tb数组的方式]).draw(false);进行数据的动dyu

ar t=$("#example").DataTable({
         "paging":   false,
        "ordering": false,
        "searching": false,
        "info":     false
        });

    $.each(ajaxdata,function(i,item){
        var cellvalues=[];
        for(var j=0;j<6;j++)
        {
            cellvalues.push(item[titles[j].toString()].toString());

        }

        //alengthd(cellvalues).drcellvalues).draw(false);   })

1.4使某一个字段变为可编-


(“table tr”).find(“td:eq(4)”).each(function(){

  var obj_text = $(this).find("input:text");    // 判断单元格下是否有文本框

        if(!obj_text.length)   // 如果没有文本框,则添加文本框使之可以编辑

            $(this).html("<input type='text' value='"+$(this).text()+"'/>");

        else   // 如果已经存在文本框,则将其显示为文本框修改的值

            $(this).html(obj_text.val()); 
    })

$("#btsave").on("click",function(){

    $("table tr").find("td:eq(4)").each(function(i,item){
         var obj_text = $(item).find("input:text");    // 判断单元格下是否有文本框


            $(this).html(obj_text.val());
    })

}); 

    })

});
```

1.5 固定某一列:
https://datatables.net/extensions/fixedcolumns/examples/
https://datatables.net/extensions/fixedcolumns/examples/initialisation/left_right_columns.html

  <link rel="stylesheet" type="text/css" href="../../extensions/FixedColumns/css/fixedColumns.dataTables.css">
<style type="text/css" class="init">
    th, td { white-space: nowrap; }

    div.dataTables_wrapper {

        width: 600px;

        margin: 0 auto;

    }

var strtds="<thead><tr>";
    for(var i=0;i<titles.length;i++){
        strtds=strtds+"<th>"+titles[i]+"</th>";
        }
        strtds=strtds+"</tr></thead>";

    document.getElementById("example").innerHTML=strtds;

    var t=$("#example").DataTable({
         "paging":   false,
        "ordering": false,
        "searching": false,
        "info":     false,
        "scrollY":    "300px",
        "scrollX":    true,

        "scrollCollapse": true,

        "fixedColumns":   {

            "leftColumns": 1,

            "ri ghtColumns": 1

        }
    });

  }
    });

二、 webapi支持跨域
http://www.eggtwo.com/news/detail/161

//跨域api设置
            GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter());
//通过扩展让ASP.NET Web API支持JSONP
    public class JsonpMediaTypeFormatter : JsonMediaTypeFormatter
    {
        public string Callback { get; private set; }

        public JsonpMediaTypeFormatter(string callback = null)
        {
            this.Callback = callback;
        }

        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            if (string.IsNullOrEmpty(this.Callback))
            {
                return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
            }
            try

            {
                this.WriteToStream(type, value, writeStream, content);
                return Task.FromResult<AsyncVoid>(new AsyncVoid());
            }
            catch (Exception exception)
            {
                TaskCompletionSource<AsyncVoid> source = new TaskCompletionSource<AsyncVoid>();
                source.SetException(exception);
                return source.Task;
            }
        }

        private void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)
        {
            JsonSerializer serializer = JsonSerializer.Create(this.SerializerSettings);

using (StreamWriter streamWriter = new StreamWriter(writeStream, this.SupportedEncodings.First()))

using (JsonTextWriter jsonTextWriter = new JsonTextWriter(streamWriter) { CloseOutput = false })
            {
                jsonTextWriter.WriteRaw(this.Callback + "(");
                serializer.Serialize(jsonTextWriter, value);
                jsonTextWriter.WriteRaw(")");
            }
        }

        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
        {
            if (request.Method != HttpMethod.Get)

            {
                return this;
            }
            string callback;
            if (request.GetQueryNameValuePairs().ToDictionary(pair => pair.Key,
                 pair => pair.Value).TryGetValue("callback", out callback))
            {
                return new JsonpMediaTypeFormatter(callback);
            }
            return this;
        }

        [StructLayout(LayoutKind.Sequential, Size = 1)]
        private struct AsyncVoid
        { }
    }

三、controller与view间的传值
3.1 可用传统的方式提交表单<form method="post" action="\controller\action">
3.2 在controller端接收参数如果为post,可以将参数命名为视图页中的控件名称。
3.3 示例代码如下:

 [HttpPost]
        public async Task<ActionResult> ModifyTimes([Bind(Include = "jsontimes")]string jsontimes)         {

            List<CycleTime> cycleTimes =await db.CycleTimes.ToListAsync();


            List<CycleTime> times = JsonConvert.DeserializeObject<List<CycleTime>>(jsontimes);
            if (cycleTimes.Count > 0)
            {
                var i = 0;
                   foreach(CycleTime ct in cycleTimes)
                   {
                       //db.Entry(ct).State = EntityState.Modified;
                       ct.times = times[i].times;
                       i++;
                   }

                    await db.SaveChangesAsync();

            }
            else {

                   db.CycleTimes.AddRange(times);
                   await db.SaveChangesAsync();


            }
            return RedirectToAction("Index");

        }

3.4 controller json数据的应用

   public JsonResult BindList()
        {
            JsonResult re = new JsonResult();


            List<CycleTime> cycleTimes=db.CycleTimes.ToList();



            re.Data = JsonConvert.SerializeObject(cycleTimes);
            re.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return re;

        }

$.ajax2({
                url: '/CycleTimes/BindList',
                async: true,
                type: 'get',
                cache:false,
                success: function (dat) {
                    console.log(dat);
                    var json = JSON.parse(dat);
                    console.log(json.length);
                   $.each(json, function (i, item) {
                        var cellvalues = [];
                       for (var j = 0; j < TrackPointCodeKeys.length; j++) {
                            var v = TrackPointCodeKeys[j].toString();
                          if (v !="times")
                                cellvalues.push(item[v].toString());
                            else

                                cellvalues.push("<input type='text' value='" + item[v].toString() + "'>");
                        }
                        console.log(cellvalues);
                        t.row.add(cellvalues).draw(false);
                    })

                },
                error: function (message) {
                    alert('error:' + message.statusText);
                }
            });

四、服务器端根据客户端IP地址返回不同的页面
服务器端获得客户端的IP地址:
system.web.httpContext.current.Request.servervariables[“REMOTE_ADDR”]
在MVC控制器中做页面跳转
return redirectiontoAction(“actionname、如About ,contact”);
同一文件夹下,
return View(“About”);
不同文件夹下
return View(“Views/test/test.cshtml”)

五、MVC传递参数,对象、集合,Json
5.1 传递参数
controller
ViewBag.pt=”108”;
view
@ViewBag.pt
5.2 传递对象
controller
ViewData.Model=new pts(){id=1,namecode=”440”,name=”出口”};
view
@model 项目名.models.pt;

@Model.namecode

5.3 传递集合
controller
List pts=new List(
new pt({id=1,namecode=”440”,name=”exit”},
new pt({id=2,namecode=”180”,name=”entrance”}));
ViewData.Model=pts;
view
@model IEnumerable<项目名称.models.pt>

@foreach(pt p in Model)
{

@p.id
@p.namecode
@p.name

}

5.4 传Json
同3.4所述。

08.24 重启LCD-Project项目
一波三折,项目重启。
基于客户的系统要求,重新部署开发环境。
win7+visualstudio+access数据库+IE8(为前端基础)

已习惯了 visualstudio MVC+EF+数据库的开发框架方式, 基于展示端无需做过多的数据存储,想启用access数据库来完成这个框架.

08.25完成visualstudio MVC+EF+ACCESS数据库的框架技术性搭建,这样可以节省2000元左右的软件费用。:)

ACCESS+EF,默认的EF只有含有MSSQL的provider factory,为了让EF同样支持其它的数据库,需进一步的配置工作。
为了支持ACCESS数据库需要JetEntityFrameworkProvider,这个可以在nuget中进行安装.还要有ACCess2007数据驱动AccessDatabaseEngine.exe
安装完成后,需要重新配置web.config,配置要点如下:








<configProtectedData defaultProvider="RsaProtectedConfigurationProvider">
        <providers>
            <add name="RsaProtectedConfigurationProvider"
                type="System.Configuration.RsaProtectedConfigurationProvider,System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
                description="Uses RsaCryptoServiceProvider to encrypt and decrypt"
                keyContainerName="NetFrameworkConfigurationKey"
                cspProviderName=""
                useMachineContainer="true"
                useOAEP="false" />

            <add name="DataProtectionConfigurationProvider"
                type="System.Configuration.DpapiProtectedConfigurationProvider,System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
                description="Uses CryptProtectData and CryptUnProtectData Windows APIs to encrypt and decrypt"
                useMachineProtection="true"
                keyEntropy=""  />
        </providers>
    </configProtectedData>

5.Enable-Migrations 生成Migrations/config.cs 在con

ig.cs 中设为自动。

6.添加Dual表,id:1。

猜你喜欢

转载自blog.csdn.net/wyaspnet/article/details/54947170