iT邦幫忙

0

想請問如何按下按鈕後從controller那裏要到資料

https://ithelp.ithome.com.tw/questions/10192083

這是我昨天問的問題,方向大略上是有
可能就參考AKA大大的方向這樣

1.click片語向controller請求資料
2.在controller使用sql語法取出片語的資料
3.在controller回傳資料到前端的ajax給dialog()使用

controller的語法我想應該就沿用我之前的
只是我該如何把他叫出來?這個我想了很久還是沒頭緒,不知能否為我講解一下?
這是我的前端

<div class="row">
    <div class="col-md-12">
        @using (Html.BeginForm("AddOrUpdate", "Dispatch", new { area = "HDNurse" }, FormMethod.Post, new { @class = "form-inline" }))
        {
            @Html.HiddenFor(m => m.GUID)
            @Html.HiddenFor(m => m.CID)
            @Html.HiddenFor(m=>m.PAT_GUID)
            @Html.HiddenFor(m => m.NURSE_EMP_ID)
            @Html.HiddenFor(m => m.CRE_UID)           
            @Html.HiddenFor(m => m.MOD_UID)
           
             <div class="box box-primary">
                 <div class="box-header">
                     <h3 class="box-title">交班單</h3>
                     <button type="submit" class="btn btn-primary pull-right">儲存</button>
                     <button type="button" class="fn-back btn btn-default pull-right btn-right-margin">取消</button>
                     @if (EditMode == Constants.EditMode_Edit)
                     {
                         // 新增模式不會有刪除按鈕
                        <button type="button" class="fn-delete btn btn-default pull-right btn-right-margin"
                                data-uid="@Model.GUID" data-tip="">
                            刪除
                        </button>
                     }                                         
                 </div><!-- /.box-header -->
                 <div class="box-body">
                     <div class="form-flex-container">
                         <div class="row-flex">
                             <div class="col-label">
                                 <label class="control-label">交班日期</label>
                             </div>
                             <div class="col-input">                               
                                  @Html.TextBoxFor(m =>m.RecordDateString, new { @class = "form-control datepicker" })
                                  @Html.TextBoxFor(m => m.RecordTimeString, new { @class = "form-control timepicker" })                                                                                                   
                             </div>
                         </div><!-- /.row -->
                         <div class="row-flex">
                             <div class="col-label">
                                 <label class="control-label">
                                    交班內容
                                     <button type="button" class="fn-phrase btn btn-default" data-toggle="modal" data-target="#myModal">片語</button>
                                 </label>
                             </div>
                             <div class="col-input">
                                 @Html.TextAreaFor(m => m.CONTENT, new { @class = "form-control" })
                             </div>
                         </div><!-- /.row -->
                     </div><!-- /.form-flex-container -->
                 </div><!-- /.box-body -->
              </div><!-- /.box -->
        }<!-- /.form -->
    </div><!-- /.col -->
</div><!-- row -->

這是我想呼叫的資料
https://ithelp.ithome.com.tw/upload/images/20190103/20110132xTi5jzedXg.jpg

其資料所使用的controller

  public ActionResult HDPhraseList(HDPhraseQueryViewModel model)
        {
            HDPhraseService hpsrvc = new HDPhraseService();
            model.phrases = hpsrvc.FindPhrase(SessionUserInfo().CID,model.OPERATING,model.TITLE);
            if (model.phrases == null) model.phrases = new List<HDPhraseDto>();
            model.OperatingOptions = GetOperatingOptions();
            return View(model);
        }

我寫的AJAX

    $('button').on('click', function () {
        $.ajax({
            type: "POST",
            url: '@Url.Action("HDPhraseList", "HDPhrase")',       
            dataType: "json",
            success: function () { alert('Success'); },
            error: function () { alert('A error'); }
        });
    })

執行結果是顯示A error,想請問我是錯在哪?

kyoe iT邦新手 5 級 ‧ 2019-01-03 13:30:34 檢舉
ajax?
see. https://stackoverflow.com/questions/22759087/submitting-modal-form-via-ajax
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
暐翰
iT邦大師 1 級 ‧ 2019-01-03 15:08:46
最佳解答

執行結果是顯示A error,想請問我是錯在哪?

回答:
你ajax使用json格式,回傳資料也要為json資料,如圖片
直接return View(Model)是不符合json格式的,所以返回Error
2019-01-03.15.16.09-image.png

解決方式可以使用return Json(Model);,如以下的DEMO


你可以參考我寫的以下程式了解JQuery Dialog過程,這邊附上線上測試demo連結 : JQuery Dialog Demo | C# Online Compiler | .NET Fiddle

Controller:

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

namespace AjaxJqueryDialog.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult GetFakeData(string name)
        {
            return Json(
                new Dictionary<string, string>
                {
                    {"Name",name }
                }
            );
        }
    }
}

View:


@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>JQuery Dialog Demo</title>
    <link href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.12.1/themes/vader/jquery-ui.css" rel="stylesheet" />
</head>
<body>
    <div>
        @using (Ajax.BeginForm(actionName: "GetFakeData", ajaxOptions: new AjaxOptions
        {
            HttpMethod = "Post",
            OnSuccess = "GetFakeDataSuccess"
        }))
        {
            <label>AjaxHelper版本查詢</label>
            <input type="text" name="name" value="ITWeiHan" />
            <input type="submit" value="查詢" />
        }
        <hr />
        <div id="formID">
            <label>JQueryAjax版本查詢</label>
            <input type="text" name="name" value="ITWeiHan" />
            <button>查詢</button>
        </div>
        
    </div>
    <div id="dialog" title="Dialog視窗"></div>


    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.unobtrusive-ajax/3.2.5/jquery.unobtrusive-ajax.js"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.12.1/jquery-ui.min.js"></script>
    <script>
        function GetFakeDataSuccess(obj) {
            var dialog = $("#dialog");
            console.log(obj);
            dialog.html(`名字 : ${obj.Name}`);
            dialog.dialog();
        }

        $('button').on('click', function () {
            $.ajax({
                type: "POST",
                url: '@Url.Action("GetFakeData", "Home")',
                data: $("#formID").find('select, textarea, input').serialize(), /*假如想要在Div像Form序列化,可以使用find input*/
                dataType: "json",
                success: function (obj) { GetFakeDataSuccess(obj); },
                error: function (e) { console.log(e); }
            });
        })
    </script>

</body>
</html>

效果圖:
2019-01-03.15.52.44-image.png

看更多先前的回應...收起先前的回應...
Homura iT邦高手 1 級 ‧ 2019-01-04 09:01:43 檢舉

新手學ajax一堆東西得搞懂
當初也是卡了很久/images/emoticon/emoticon16.gif

暐翰 iT邦大師 1 級 ‧ 2019-01-04 09:27:17 檢舉

沒錯,過了Ajax又有WebSocket...

小魚 iT邦大師 1 級 ‧ 2019-01-04 13:58:26 檢舉

應該是前端跟後端會分不清楚吧,
新手基本上這部份會搞不懂,
最後全部一起端了!
/images/emoticon/emoticon39.gif

暐翰 iT邦大師 1 級 ‧ 2019-01-04 14:50:13 檢舉

對,這是新人幾乎都會面對的檻

tenno081 iT邦研究生 4 級 ‧ 2019-01-04 16:15:15 檢舉

我的前端滿爛的/images/emoticon/emoticon02.gif
之前上課前端的部分也只算是點水過,然後我現在工作的地方
前端也不是用很兇,但要用到時就像現在一樣慘兮兮/images/emoticon/emoticon02.gif

暐翰 iT邦大師 1 級 ‧ 2019-01-04 16:26:11 檢舉

tenno081
我遇到滿多 小前端 + 大後端 的需求
前端也不用太好,JQuery + Ajax + Bootstrap基本夠用

另外上面回答有解決你的問題嗎?

tenno081 iT邦研究生 4 級 ‧ 2019-01-04 16:41:51 檢舉

老實說沒有,真的很抱歉/images/emoticon/emoticon06.gif
我後來是這樣弄

$('button').on('click', function () {
        $.ajax({
            type: "POST",
            url: '@Url.Action("HDPhraseList", "HDPhrase")',       
            dataType: Json(Model),
            success: function () { alert('Success'); },
            error: function () { alert('A error'); }
        });
    })

然後就顯示這樣
https://ithelp.ithome.com.tw/upload/images/20190104/201101328sm6s3jR9I.jpg
不知道能否請問有沒有AJAX+資料庫的相關文章,我找不太到我想找的
資料,我覺得我真不受教,看了範例還是解不出,我的主管是跟我說他希望能做成元件,之後會給我一版,但還是很謝謝您。

暐翰 iT邦大師 1 級 ‧ 2019-01-04 16:49:10 檢舉

不是這樣改的....
請看圖片
2019-01-04.16.48.49-image.png

Controller改為

public ActionResult HDPhraseList(HDPhraseQueryViewModel model)
{
    HDPhraseService hpsrvc = new HDPhraseService();
    model.phrases = hpsrvc.FindPhrase(SessionUserInfo().CID,model.OPERATING,model.TITLE);
    if (model.phrases == null) model.phrases = new List<HDPhraseDto>();
    model.OperatingOptions = GetOperatingOptions();
    return Json(model);
}

Ajax還是一樣

$('button').on('click', function () {
    $.ajax({
        type: "POST",
        url: '@Url.Action("HDPhraseList", "HDPhrase")',       
        dataType: "json",
        success: function () { alert('Success'); },
        error: function () { alert('A error'); }
    });
})
0
Homura
iT邦高手 1 級 ‧ 2019-01-03 15:18:23

你的ajax方法裡面沒看到你把資料塞進去啊....

小魚 iT邦大師 1 級 ‧ 2019-01-04 07:36:51 檢舉

他應該只是先測試會不會成功而已...

Homura iT邦高手 1 級 ‧ 2019-01-04 09:00:34 檢舉

小魚
原來是這樣啊/images/emoticon/emoticon16.gif

我要發表回答

立即登入回答