1. 程式人生 > 其它 >Ajax 上傳圖片,修改圖片,複選框操作,聯動詳情

Ajax 上傳圖片,修改圖片,複選框操作,聯動詳情

一、Ajax圖片上傳顯示

1、控制器操作

public ActionResult UpImage()
        {
            try
            {
                //接收圖片
                var hpf = Request.Files[0];
                //將虛擬路徑轉成物理路徑
                var path = Server.MapPath("/Image/");
                //儲存
                hpf.SaveAs(path + hpf.FileName);
                
//返回圖片名稱 return Json(new { cs = 1, fileName = "/Image/" + hpf.FileName }); } catch (Exception) { return Json(new { cs = 0, fileName = "" }); throw; } }

2、在新增頁面上的操作

上傳圖片 和獲取 複選框

@{
    ViewBag.Title 
= "Add"; } <h2>新增神奇寶貝資訊</h2> <script src="~/Scripts/jquery-3.4.1.min.js"></script> <link href="~/Content/bootstrap.css" rel="stylesheet" /> <table class="table table-bordered"> <tr> <td>名稱</td> <td> <input type="
text" id="Name" style="height:30px" /> </td> </tr> <tr> <td>影象</td> <td> <input type="file" id="Photo" name="Photo" /> <img id="Img" width="100" height="70" /> <input type="button" value="上傳圖片" class="btn btn-success" onclick="UpImage()" /> </td> </tr> <tr> <td>性格</td> <td> <input type="text" id="Nature" style="width:70px;height:30px" /> </td> </tr> <tr> <td>屬性</td> <td> <input type="checkbox" id="Attribute" name="Attribute" value="" /><input type="checkbox" id="Attribute" name="Attribute" value="" /><input type="checkbox" id="Attribute" name="Attribute" value="" /><input type="checkbox" id="Attribute" name="Attribute" value="" /><input type="checkbox" id="Attribute" name="Attribute" value="" /><input type="checkbox" id="Attribute" name="Attribute" value="" /><input type="checkbox" id="Attribute" name="Attribute" value="飛行" /> 飛行 <input type="checkbox" id="Attribute" name="Attribute" value="地面" /> 地面 <input type="checkbox" id="Attribute" name="Attribute" value="岩石" /> 岩石 <input type="checkbox" id="Attribute" name="Attribute" value="超能" /> 超能 <input type="checkbox" id="Attribute" name="Attribute" value="幽靈" /> 幽靈 </td> </tr> <tr> <td>性別</td> <td> <input type="radio" id="Sex" name="Sex" value="true" checked="checked"/><input type="radio" id="Sex" name="Sex" value="false" /></td> </tr> <tr> <td>年齡</td> <td> <input type="text" id="Age" style="width:70px;height:30px" /> </td> </tr> <tr> <td>生活地區</td> <td> <select id="Place" onclick="Region()"> <option>請選擇</option> </select> <select id="Region"> <option>請選擇</option> </select> </td> </tr> <tr> <td></td> <td> <input type="button" value="新增" onclick="Add()" /> <input type="button" value="取消" onclick="location.href='/User/Index'" /> </td> </tr> </table> <script> $(function () { Place(); }) //地區 function Place() { $.get('http://localhost:55145/api/User/GetPlace/' + 0, res => { $(res).each(function () { $("#Place").append('<option value="' + this.NId + '">' + this.Place + '</option>'); }) }) } //區域 function Region() { $("#Region").empty(); var id = $("#Place").val(); $.get('http://localhost:55145/api/User/GetPlace/' + id, res => { $("#Region").empty(); $("#Region").append("<option>請選擇</option>"); $(res).each(function () { $("#Region").append('<option value="' + this.NId + '">' + this.Place + '</option>'); }) }) } //上傳 圖片 function UpImage() { //FormDate js當中的一個表單的物件 var fd = new FormData(); fd.append("Photo", $("#Photo")[0].files[0]); //一定是ajax 方式上傳 請求一定是POST $.ajax({ url: 'UpImage', type: 'post', dataType: 'json', data: fd, contentType: false,//不限制類型 processData: false,//預設 success: function (data) { if (data.cs == 1) { //圖片預覽 $("#Img").attr("src", data.fileName); } } }) } //新增 function Add() { var sz = []; $('[name=Attribute]:checked').each(function () { sz.push(this.value); }) $.post('http://localhost:55145/api/User/Add', { Name: $("#Name").val(), Photo: $("#Photo")[0].files[0].name, Nature: $("#Nature").val(), Attribute: sz.toString(), Sex: $("[name=Sex]:checked").val(), Age: $("#Age").val(), PlaceId: $("#Place").val(), RegionId: $("#Region").val(), }, res => { if (res > 0) { alert("新增成功"); location.href = '/User/Index'; } else { alert("新增失敗"); } }) } </script>

3、在顯示頁面的操作

$(res.list).each(function () {
                var arr = '<tr>'
                    + '<td><input type="checkbox"  name="box" value="' + this.Id + '" /></td>'
                    + '<td>' + this.Name + '</td>'
                    + '<td><img src="/Image/' + this.Photo + '" width="100" height="70" /></td>'
                    + '<td>' + this.Nature + '</td>'
                    + '<td>' + this.Attribute + '</td>'
                    + '<b><td style="color:' + (this.Sex ? "blue" : "deeppink") + '">' + (this.Sex ? "" : "") + '</td></b>'
                    + '<td>' + this.Age + '</td>'
                    + '<td>' + this.PlaceIdName + '' + this.RegionIdName + '</td>'
                    + '<td><a href="Edit?id='+this.Id+'">編輯</a>-<a href="#" onclick="Delete(' + this.Id + ')">刪除</a></td>'
                    + '</tr>';
                $("#list").append(arr);
            })

4、編輯詳情和編輯修改操作

解:頁面顯示和新增一樣

function GetBianJi() {
        $.get('http://localhost:55145/api/User/GetBianJi/' + id, res => {
            $("#Name").val(res.Name);
            $("#Img").attr("src", "/Image/" + res.Photo);
            //定義的全域性變數等於圖片名
            lamg = res.Photo;
            $("#Nature").val(res.Nature);
            //複選框數值迴圈顯示
            var ce = res.Attribute;
            $("[name=Attribute]").each(function () {
                if (ce.indexOf($(this).val()) > -1) {
                    $(this).prop("checked", true);
                }
                else {
                    $(this).prop("checked", false);
                }
            })
            //單選
            $("[name=Sex][value=" + res.Sex + "]").prop("checked", true);
            $("#Age").val(res.Age);
            $("#Place").val(res.PlaceId);
             //第二個聯動下拉框
            Region();
            $("#Region").val(res.RegionId);
        })
    }

    function Update() {
        //判斷圖片是否存在
        var tup = $("#Photo").val();
        if (tup != null) {
            //$("#Photo").attr("src")
            tup = lamg;//圖片名稱
        }
        else {
            Photo: $("#Photo")[0].files[0].name;//不存在為空
        }
        //複選框的陣列
        var sz = [];
        $('[name=Attribute]:checked').each(function () {
            sz.push(this.value);
        })

        $.post('http://localhost:55145/api/User/Updatabase', {
            Id:id,
            Name: $("#Name").val(),
            Photo: tup,
            Nature: $("#Nature").val(),
            Attribute: sz.toString(),
            Sex: $("[name=Sex]:checked").val(),
            Age: $("#Age").val(),
            PlaceId: $("#Place").val(),
            RegionId: $("#Region").val(),
        }, res => {
                if (res > 0) {
                    alert("修改成功");
                    location.href = '/User/Index';
                }
                else {
                    alert("修改失敗");
                }
        })
    }
5、修改時獲取聯動詳情
    //修改傳的ID
    var id = location.search.substring(4);
    var lamg = '';
    $(function () {
        $.ajaxSettings.async = false;
        //第一個聯動下拉框
        Place();
        GetBianJi();
        $.ajaxSettings.async = true;
    })