C#.Net前端数据post传递方法(mvc)

原创 2017年11月17日 09:27:28

Model :Entity实体模型中的数据组织,对应sql数据库中的表建立相应的类库

这里写图片描述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Entity
{
    /// <summary>
    /// 焦点图
    /// </summary>
    [Serializable]
    public partial class FocusImg
    {
        public FocusImg()
        { }
        #region Model
        private int _id;
        private string _ImgSrc;
        private string _Url;
        private string _Title;
        private DateTime? _BgTime;
        private DateTime? _EndTime;
        private bool? _State;
        #endregion

        public int Id
        {
            set { _id = value; }
            get { return _id; }
        }
        public string ImgSrc
        {
            set { _ImgSrc = value; }
            get { return _ImgSrc;  }
        }
        public string Url
        {
            set { _Url = value; }
            get { return _Url; }
        }
        public string Title
        {
            set { _Title = value; }
            get { return _Title; }
        }
        public DateTime? BgTime
        {
            set { _BgTime = value; }
            get { return _BgTime; }
        }
        public DateTime? EndTime
        {
            set { _EndTime = value; }
            get { return _EndTime; }
        }
        public bool? State
        {
            set { _State = value; }
            get { return _State; }
        }

    }
}
//其中 public DataTime? BgTime {}  中的 数据类型加?问号,表示该值可以为空值

在Controllers控制器中,实现FocusImg类与数据库中进行交互


namespace Dal
{///....
#region 图片上传
public static string jiaodiantu()
{
 //SqlHerper类是自定义的数据库交互类,将原本的sql语句进行简化
    var dt = SqlHelper.ExecuteDataTable("SELECT *  FROM dbo.FocusImg ");
    return JsonHelper.DataTableToJSON(dt);
}
///....
}
#endregion


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Entity;
using Tools;
using Webdiyer.WebControls.Mvc;
using Dal;
namespace WebSite.Controllers
{
    public class AdminController : Controller
    {
        // GET: Admin
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult jiaodiantu()
        {
            var json = SiteDal.jiaodiantu();
            var fImgData = JsonHelper.JSONToObject<List<FocusImg>>(json);

            return View(fImgData);
        }

        [HttpPost]
        public ActionResult SaveJiaoDianTuData(FocusImg data)
        {
            var postData = data;

            string code = postData.ImgSrc;
            //base64编码转存成图片
            string codeBase64 = code.Split(',')[1];

            byte[] bytes = Convert.FromBase64String(codeBase64);

            //以时间序列命名图片文件
             DateTime now = DateTime.Now;
            string dtString = now.Year.ToString()
            + now.Month.ToString().PadLeft(2, '0')
            + now.Day.ToString().PadLeft(2, '0')
            + now.Hour.ToString().PadLeft(2, '0')
            + now.Minute.ToString().PadLeft(2, '0')
            + now.Second.ToString().PadLeft(2, '0')
            + now.Millisecond.ToString().PadLeft(3, '0');

            string fileName = dtString + ".jpg";
            string filePath = "~/images/Focus/" + fileName;
            ///映射为物理路径

            string fullPath = Server.MapPath(filePath);

            System.IO.File.WriteAllBytes(fullPath, bytes);


            int state = 0;
            if(postData.State==true)
            {
                state = 1;
            }

            string cmdText = $@"
                            INSERT dbo.FocusImg
                                     ( ImgSrc ,
                                       Url ,
                                       Title ,
                                       BgTime ,
                                       EndTime ,
                                       State
                                     )
                             VALUES  ( N'{fileName} ' , -- ImgSrc - nvarchar(1000)
                                       N'{postData.Url}' , -- Url - nvarchar(1000)
                                       N'{postData.Title}' , -- Title - nvarchar(1000)
                                       GETDATE() , -- BgTime - datetime
                                      DATEADD(MONTH,1,GETDATE()) , -- EndTime - datetime
                                       {state}  -- State - bit
                                     )
                                ";
            SqlHelper.ExecuteNonQuery(cmdText);

          //  img.Save("~/images/Focus/a.jpg");


            return Content(" ");
        }
    }
}

在View视图中,对前端的页面进行编辑cshtml类型文件

@model System.Collections.Generic.List<Entity.FocusImg>

@{
    ViewBag.Title = "title";
    Layout = "~/Views/Admin/_Layout.cshtml";
}


<script type="text/javascript">
    function submitImgClick() {
        var fileName = document.getElementById("imgFile").files;
        var img = $("#imgDiv").children("img").attr('src');    
        var statePost = $("#state option:selected").text();
        var stateNum = false;
        if (statePost == "公开")
        {
            stateNum = true;
        }     

        $.post("/Admin/SaveJiaoDianTuData",
            { Title: $("#Title").val(), ImgSrc:img, Url: $("#Url").val(), State: stateNum },
            function (result) {

            });       
        $(location).attr('href', 'jiaodiantu');

    }



    function uploadImg(){
        window.open("uploadImg.aspx");
    }

    //修改数据,以及数据库中该条数据修改
    function imgAlter(id) {
        //var tr = document.getElementById(id);
        //alert(tr.rows.cells[0].innerHTML);

    }

    //删除table.row数据,以及数据库中的改数据(id)
    function imgDelete(id) {
        //
        var tr = document.getElementById(id);
        tr.parentNode.removeChild(tr);
    }

</script>

@*<button class="btn" onclick="uploadImg()">上传图片</button>*@
<a data-toggle="modal" href="#modalDefault" class="btn ">上传数据</a>

<!-- Table Hover 图片列表-->
<div class="block-area" id="tableHover">
    <h2 class="block-title">图片列表</h2>
    <div class="table-responsive overflow">
        <table class="table table-bordered table-hover tile" id="imgTable">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>图片</th>
                    <th>图片位置</th>
                    <th>链接地址</th>
                    <th>标题</th>
                    <th>开始时间</th>
                    <th>结束时间</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                @{
                    foreach (var item in Model)
                    {
                        <tr id="@item.Id">
                            <td>@item.Id</td>
                            <td><img src="~/images/Focus/@item.ImgSrc" style="width:250px;height:120px;"> </td>
                            <td>@item.ImgSrc</td>
                            <td>@item.Url</td>
                            <td>@item.Title</td>
                            <td>@item.BgTime</td>
                            <td>@item.EndTime</td>
                            <td>@item.State</td>
                            <td>                                
                                <a  data-toggle="modal" href="#modalNarrower" class="btn btn-sm" onclick="imgAlter(@item.Id)">修改</a>
                                <button id="imgDele" class="btn btn-sm " onclick="imgDelete(@item.Id)">删除</button>                            

                            </td>
                        </tr>
                    }
                }
            </tbody>
        </table>
    </div>
</div>



<!-- Modal Default  上传图片弹窗-->
<div class="modal fade" id="modalDefault" tabindex="-1" role="dialog" aria-hidden="true" style="display: none;">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h1 class="modal-title">图片上传</h1>
            </div>
            <div class="modal-body">
                <h3> 标题</h3>
                <input type="text" class="form-control m-b-10" placeholder="Default" id="Title"><br />

                <h3>上传图片</h3>
                <div class="fileupload fileupload-new" data-provides="fileupload">
                    <input type="hidden" value="">
                    <div id="imgDiv" class="fileupload-preview thumbnail form-control"></div>

                    <div>
                        <span class="btn btn-file btn-alt btn-sm">
                            <span class="fileupload-new">选择图片</span>
                            <span class="fileupload-exists">Change</span>
                            <input id="imgFile" type="file" name="">
                        </span>
                        <a href="#" class="btn fileupload-exists btn-sm" data-dismiss="fileupload">Remove</a>
                    </div>
                </div>

                <br />
                <h3>链接地址</h3>
                <input type="text" class="form-control m-b-10" placeholder="Default" id="Url" ><br />
                <h3>状态</h3>
                <select class="form-control m-b-10" id="state">
                    <option>公开</option>
                    <option>私密</option>                    
                </select>



            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-sm" id="submitImg" onclick="submitImgClick()"  >保存更改</button>
                <button type="button" class="btn btn-sm" data-dismiss="modal">取消</button>

                @*<button type="submit" class="btn btn-info btn-sm m-t-10">SUBMIT FORM</button>*@

            </div>
        </div>
    </div>
</div>


 <!-- Modal Narrower 修改图片弹窗 -->
<div class="modal fade" id="modalNarrower" tabindex="-1" role="dialog" aria-hidden="true" style="display: none;">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title">修改图片</h4>
            </div>
            <div class="modal-body" id="modalBody">
                <h3> 标题</h3>

                <input type="text" class="form-control m-b-10" placeholder="Default" id="inputTitle" value="Table表获取数据"><br />
                <h3>上传图片</h3>
                <div class="fileupload fileupload-new" data-provides="fileupload">
                    <input type="hidden" value="" name="">
                    <div class="fileupload-preview thumbnail form-control">
                    </div>
                    <div>
                        <span class="btn btn-file btn-alt btn-sm">
                            <span class="fileupload-new">Select image</span>
                            <span class="fileupload-exists">Change</span>
                            <input type="file" name="">
                        </span>
                        <a href="#" class="btn fileupload-exists btn-sm" data-dismiss="fileupload">Remove</a>
                    </div>
                </div>
                <br />
                <h3>链接地址</h3>
                <input type="text" class="form-control m-b-10" placeholder="Default" id="inputUrl" value="Table表获取数据"><br />

                <h3>状态</h3>
                <select class="form-control m-b-10">
                    <option>公开</option>
                    <option>私密</option>
                </select>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-sm" onclick="">保存修改</button>
                <button type="button" class="btn btn-sm" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>

<!-- Javascript Libraries -->
<!-- jQuery -->
<script src="js/jquery.min.js"></script> <!-- jQuery Library -->
<script src="js/jquery-ui.min.js"></script> <!-- jQuery UI -->
<!-- Bootstrap -->
<script src="js/bootstrap.min.js"></script>
<!--  Form Related -->
<script src="js/validation/validate.min.js"></script> <!-- jQuery Form Validation Library -->
<script src="js/validation/validationEngine.min.js"></script> <!-- jQuery Form Validation Library - requirred with above js -->
<script src="js/select.min.js"></script> <!-- Custom Select -->
<script src="js/chosen.min.js"></script> <!-- Custom Multi Select -->
<script src="js/datetimepicker.min.js"></script> <!-- Date & Time Picker -->
<script src="js/colorpicker.min.js"></script> <!-- Color Picker -->
<script src="js/icheck.js"></script> <!-- Custom Checkbox + Radio -->
<script src="js/autosize.min.js"></script> <!-- Textare autosize -->
<script src="js/toggler.min.js"></script> <!-- Toggler -->
<script src="js/input-mask.min.js"></script> <!-- Input Mask -->
<script src="js/spinner.min.js"></script> <!-- Spinner -->
<script src="js/slider.min.js"></script> <!-- Input Slider -->
<script src="js/fileupload.min.js"></script> <!-- File Upload -->
<!-- Text Editor -->
<script src="js/editor2.min.js"></script> <!-- WYSIWYG Editor -->
<script src="js/markdown.min.js"></script> <!-- Markdown Editor -->
<!-- UX -->
<script src="js/scroll.min.js"></script> <!-- Custom Scrollbar -->
<!-- Other -->
<script src="js/calendar.min.js"></script> <!-- Calendar -->
<script src="js/feeds.min.js"></script> <!-- News Feeds -->
<!-- All JS functions -->
<script src="js/functions.js"></script>

使用post方法将前端页面值传到数据库

function submitImgClick() {
        var fileName = document.getElementById("imgFile").files;
        var img = $("#imgDiv").children("img").attr('src');    
        var statePost = $("#state option:selected").text();
        var stateNum = false;
        if (statePost == "公开")
        {
            stateNum = true;
        }     

        $.post("/Admin/SaveJiaoDianTuData",
            { Title: $("#Title").val(), ImgSrc:img, Url: $("#Url").val(), State: stateNum },
            function (result) {

            });       
        $(location).attr('href', 'jiaodiantu');

    }

使用razor读取Model中的可以用@{//嵌入Html页面的方法}

 <tbody>
                @{
                    foreach (var item in Model)
                    {
                        <tr id="@item.Id">
                            <td>@item.Id</td>
                            <td><img src="~/images/Focus/@item.ImgSrc" style="width:250px;height:120px;"> </td>
                            <td>@item.ImgSrc</td>
                            <td>@item.Url</td>
                            <td>@item.Title</td>
                            <td>@item.BgTime</td>
                            <td>@item.EndTime</td>
                            <td>@item.State</td>
                            <td>                                
                                <a  data-toggle="modal" href="#modalNarrower" class="btn btn-sm" onclick="imgAlter(@item.Id)">修改</a>
                                <button id="imgDele" class="btn btn-sm " onclick="imgDelete(@item.Id)">删除</button>                            

                            </td>
                        </tr>
                    }
                }

【C#.NET】dataGridView查询SQL数据方法

//查询数据         public void selecetdata()//如果不是static 就要实例化才能调用 ,         {             try      ...

ASP.NET MVC 中将数据从View传递到控制器中的三种方法(表单数据绑定)

ASP.NET MVC 中将数据从View传递到控制器中的三种方法(表单数据绑定) 在ASP.NET MVC框架中,将视图中的数据传递到控制器中,主要通过发送表单实现的.具体使用中,主要使用...
  • Litt_J
  • Litt_J
  • 2014年12月29日 21:41
  • 2767

ASP.NET MVC使用jQuery来POST数据至数据库中

学习ASP.NET MVC程序,结合jQuery客户端代码,Post数据至数据库去。Insus.NET今天写一个完整性的例子。 在数据库中,创建一个表[dbo].[TestUser]: ...
  • linybo
  • linybo
  • 2015年03月27日 10:11
  • 846

C#.net模拟提交表单GET、POST

方法一、System.Net.WebClient WebClientObj         = new System.Net.WebClient();    System.Collections.Sp...

编辑技巧——c#.net.mvc.jquery:异步刷新

在做到一个项目关于

编程思路——c#.net mvc 项目经验:三级联动框

项目要求: 单击

C#.NET MVC 枚举转dictionary自动装载生成下拉框

C#MVC开发中经常会遇到生成下拉框的情况,往往下拉框的内容会跟枚举进行关联,此代码是读取枚举字段的描述内容作为下拉框text值(当描述不存在时取字段名称),枚举的value作为下拉框的value值自...

编程思路———c#.net.mvc:字典

这次这个项目和上次的中图分类基本类似。

ASP.NET接受GET和POST数据终极方法实例

using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Syst...
  • wzwlln
  • wzwlln
  • 2011年02月12日 11:34
  • 13897
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:C#.Net前端数据post传递方法(mvc)
举报原因:
原因补充:

(最多只允许输入30个字)