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

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

C#.Net前端数据post传递方法(mvc)_第1张图片

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

namespace Entity
{
    /// 
    /// 焦点图
    /// 
    [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>(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>


<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.Idtd>
                            <td><img src="~/images/Focus/@item.ImgSrc" style="width:250px;height:120px;"> td>
                            <td>@item.ImgSrctd>
                            <td>@item.Urltd>
                            <td>@item.Titletd>
                            <td>@item.BgTimetd>
                            <td>@item.EndTimetd>
                            <td>@item.Statetd>
                            <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>




<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">Changespan>
                            <input id="imgFile" type="file" name="">
                        span>
                        <a href="#" class="btn fileupload-exists btn-sm" data-dismiss="fileupload">Removea>
                    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 FORMbutton>*@

            div>
        div>
    div>
div>


 
<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 imagespan>
                            <span class="fileupload-exists">Changespan>
                            <input type="file" name="">
                        span>
                        <a href="#" class="btn fileupload-exists btn-sm" data-dismiss="fileupload">Removea>
                    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>



<script src="js/jquery.min.js">script> 
<script src="js/jquery-ui.min.js">script> 

<script src="js/bootstrap.min.js">script>

<script src="js/validation/validate.min.js">script> 
<script src="js/validation/validationEngine.min.js">script> 
<script src="js/select.min.js">script> 
<script src="js/chosen.min.js">script> 
<script src="js/datetimepicker.min.js">script> 
<script src="js/colorpicker.min.js">script> 
<script src="js/icheck.js">script> 
<script src="js/autosize.min.js">script> 
<script src="js/toggler.min.js">script> 
<script src="js/input-mask.min.js">script> 
<script src="js/spinner.min.js">script> 
<script src="js/slider.min.js">script> 
<script src="js/fileupload.min.js">script> 

<script src="js/editor2.min.js">script> 
<script src="js/markdown.min.js">script> 

<script src="js/scroll.min.js">script> 

<script src="js/calendar.min.js">script> 
<script src="js/feeds.min.js">script> 

<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.Idtd>
                            <td><img src="~/images/Focus/@item.ImgSrc" style="width:250px;height:120px;"> td>
                            <td>@item.ImgSrctd>
                            <td>@item.Urltd>
                            <td>@item.Titletd>
                            <td>@item.BgTimetd>
                            <td>@item.EndTimetd>
                            <td>@item.Statetd>
                            <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>
                    }
                }

你可能感兴趣的:(web基础)