iT邦幫忙

0

MVC 使用 Ajax.BeginForm 的問題?

Luke 2018-07-04 10:07:291497 瀏覽

Index.cshtml

@model com...略...MIAViewModel
@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "ajaxTargetHeaderDiv", Url = Url.Action("BodyResult") }))
{
   @Html.Partial("Query")
}
<div id="ajaxTargetHeaderDiv"></div>
<div id="ajaxTargetDetailDiv"></div>

Query.cshtml

@model com...略...MIAViewModel
<table style="width:100%; border-spacing:0;" border="1">
    <thead>
        <tr>
            <th class="header">@Html.LabelFor(m => m.MATERIAL)</th>
            <td>
                @Html.TextBoxFor(m => m.MATERIAL)
                @Html.ValidationMessageFor(m => m.MATERIAL, "", new { @class = "error" })
            </td>
            <th class="header">@Html.LabelFor(m => m.BATCH)</th>
            <td>
                @Html.TextBoxFor(m => m.BATCH)
                @Html.ValidationMessageFor(m => m.BATCH, "", new { @class = "error" })
            </td>
        </tr>
        ...略...
        <tr>
            <td colspan="4" align="right"><input type="submit"></td>
        </tr>
    </thead>
</table>

BodyResult.cshtml

@model com...略...MIAViewModel
<table style="width:100%; border-spacing:0;" class="table table-bordered table-striped">
    <thead>
        <tr>
            <td class="headerByTable"> </td>
            <td class="headerByTable">工單</td>
            <td class="headerByTable">料號</td>
            ...略...
            <td class="headerByTable">TECO</td>
        </tr>
    </thead>
 @if (null != Model && null != Model.HeaderList)
    {
        foreach (var item in Model.HeaderList)
        {
            <tr>
                <td>
                    @using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "ajaxTargetDetailDiv", Url = Url.Action("CollaoseDetail") }))
                    {
                        <button type="submit" class="btn">expand</button>
                        <input type="hidden" id="@item.ORDERID" name="Order" value="@item.ORDERID" />
                    }
                </td>
                <td>@item.ORDERID</td>
                ...略...
                <td>@item.TECO</td>
            </tr>
        }
    }
</table>

CollaoseDetail.cshtml

@model com...略...MIAViewModel
<table style="width:100%; border-spacing:0;" class="table table-bordered table-striped">
<tr>...略...
</table>
</table>

當點選【< button type="submit" class="btn">expand< /button >】
會去執行Action ==>CollaoseDetail
將資料載入到 Index.cshtml的< div id="ajaxTargetDetailDiv">< /div >

請問【< button type="submit" class="btn">expand< /button >】
點選後怎樣去改【< button type="submit" class="btn">Collaose< /button >】?
點選另一個的時候,原本的還要改回來expand?

1
暐翰
iT邦大師 2 級 ‧ 2018-07-04 14:11:09
最佳解答

效果圖:

線上測試連結

MVC放成各一個處理,JS使用CDN
所以很方便測試跟移植。

邏輯:

1.把生成的button綁定click方法
2.點擊變更button text
3.因為使用ajax beginform所以要注意點擊時要去改變type為非submit
要不然縮小會沒有效果
4.QueryHead方法為甚麼要拼接ajax beginform
原因是.Net Fiddle不支援多CSHTML (也可以看一下beginform的原貌)

Models:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;

namespace AjaxBeginForm_ITMan.Models
{
    public class Test
    {
        public static List<ITAccountModel> TestDatas = new List<ITAccountModel>();
        static Test()
        {
            TestDatas.Add(
                new ITAccountModel
                {
                    Account = "IT01",
                    Name = "阿翰",
                    Favorite = "C#、Java、Oracle...",
                    Age = 24
                }
            );
            TestDatas.Add(
                new ITAccountModel
                {
                    Account = "IT02",
                    Name = "小明",
                    Favorite = "Java、MYSQL...",
                    Age = 25
                }
            );
            TestDatas.Add(
                new ITAccountModel
                {
                    Account = "IT03",
                    Name = "小朱",
                    Favorite = "JS、PHP...",
                    Age = 55
                }
            );
        }
    }

    public class ITAccountModel
    {
        [DisplayName("帳號")]
        public string Account { get; set; }
        [DisplayName("名稱")]
        public string Name { get; set; }
        [DisplayName("喜好")]
        public string Favorite { get; set; }
        [DisplayName("年紀")]
        public int Age { get; set; }
    }
}

View:

 @{
    Layout = null;
}
@model AjaxBeginForm_ITMan.Models.ITAccountModel

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>IT AjaxBeginForm</title>
    <link href='https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet' type='text/css' />
</head>
<body>
    <div class='container body-content'>
        <br />
        <h3>查詢:</h3>
        @using (Ajax.BeginForm(new AjaxOptions
        {
            UpdateTargetId = "ajaxTargetHeaderDiv",
            Url = Url.Action("QueryHead")
        }))
        {

            <select name="Account">
                <option value="null">null</option>
                <option value="IT" selected>IT</option>
                <option value="IT01">IT01</option>
                <option value="IT02">IT02</option>
            </select>
            <button type='submit' class='btn'>查詢</button>
        }
        <hr />
        <h3>資料:</h3>
        <div id='ajaxTargetHeaderDiv'></div>

        <div id='ajaxTargetBodyDiv'></div>
    </div>

    <script>
        function clickQuery(e) {
            var btn = $(e);
            if (btn.text() == '展開') {
                //先把所有按鈕回復原狀
                var allbtns = $("#ajaxTargetHeaderDiv button")
                allbtns.text('展開');
                allbtns.attr('type', 'submit');
                console.log(allbtns);

                //處理個別按鈕
                btn.attr('type', 'submit');
                btn.text('縮小');
            }
            else {
                btn.text('展開');
                btn.attr('type', 'button');
                $("#ajaxTargetBodyDiv").html('')
                return;
            }
        }
    </script>

    <script src='https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js'></script>
    <script src='https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js'></script>
    <script src='https://ajax.aspnetcdn.com/ajax/jquery.unobtrusive-ajax/3.2.5/jquery.unobtrusive-ajax.min.js'></script>
</body>
</html>

Control

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace AjaxBeginForm_ITMan.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult QueryHead(string Account)
        {
            var datas = AjaxBeginForm_ITMan.Models.Test.TestDatas
                .Where(w => w.Account.Contains(Account)).ToList();
            if (datas.Count == 0)
                return Content("沒有資料");
            else
                return Content(
                     string.Join("<br>", datas.Select(data => @"
                        <form action='~/Home/Index' data-ajax='true' 
                            data-ajax-mode='replace' 
                            data-ajax-update='#ajaxTargetBodyDiv' 
                            data-ajax-url='"+Url.Action("QueryBody")+@"' id='form1' method='post'> 
                            帳號 : "+data.Account+" , 名稱 : "+data.Name+@"
                            <input type='hidden' name='Account' value='"+data.Account+@"' />
                            <button type='submit' class='btn' onclick='clickQuery(this)'>展開</button>
                        </form>
                    "))
            );
        }

        public ActionResult QueryBody(string Account)
        {
            var data = AjaxBeginForm_ITMan.Models.Test.TestDatas
                .Where(w => w.Account == Account).SingleOrDefault();
            if (data == null)
                return Content(@"
                    <hr />
                    <h3>明細:</h3>
                    沒有資料"
                );
            else
                return Content(@"
                    <hr />
                    <h3>明細:</h3>
                    喜好 : "+data.Favorite+" , 年紀 : "+data.Age+@"
                ");
        }
    }
}

你先看一下,假如有問題再跟我說 :)

Luke iT邦新手 3 級 ‧ 2018-07-04 14:52:13 檢舉

/images/emoticon/emoticon07.gif
都看得懂
謝謝

0
Homura
iT邦高手 2 級 ‧ 2018-07-04 11:27:35

看你的頁面很多還是在前端修改吧....

BodyResult.cshtml

<button type="submit" class="btn" id="expand">expand</button>
<button type="submit" class="btn" id="Collaose">另一顆按鈕</button>
@section scripts{

    <script>
        $('#expand').click(function () {    
            $(this).val('Collaose');          
        });        
        $('#Collaose').click(function () {
               $(this).val('expand');
        });

    </script>
}
Luke iT邦新手 3 級 ‧ 2018-07-04 11:58:04 檢舉

/images/emoticon/emoticon06.gif

那點選另一個的
點選另一個的時候,原本的還要改回來expand?

Homura iT邦高手 2 級 ‧ 2018-07-04 12:02:00 檢舉

TWLuke
一樣在寫個click事件給另一顆按鈕

Homura iT邦高手 2 級 ‧ 2018-07-04 13:38:39 檢舉

TWLuke
我上面修改了
如果你不太會js...
其實也可以考慮ViewBag

0
小魚
iT邦高手 1 級 ‧ 2018-07-04 12:00:41

點選submit之後, 不是就會送到後端處理了嗎?

Luke iT邦新手 3 級 ‧ 2018-07-04 13:06:47 檢舉

會到後台【Controller ==> CollaoseDetail】 撈出detail 資料

前台

Controller

public class MetalInciseAreaController : Controller
{
   public ActionResult Index()
   {
     ...略...
   }
   public ActionResult BodyResult(MIAViewModel vm,int page = 1)
   {
     ...略...
   }
   
   
    public ActionResult CollaoseDetail(MIAViewModel vm)
    {
        if (Request.IsAjaxRequest())
        {
            ...略...
            return View(vm);
        }
    ...略...
    }
}

我要發表回答

立即登入回答