如何在MVC中使用Ajax调用同时打开弹出窗口并将数据发布到控制器

时间:2018-09-04 11:52:57

标签: asp.net-mvc model-view-controller popup asp.net-ajax

我正在尝试在“表单视图”中实现搜索功能。搜索窗口会在弹出窗口中(在partialView中打开)并询问搜索查询(figure)。现在,用户输入所有搜索字段,并发出POST请求,最终弹出窗口显示搜索结果表。

表单视图 (具有打开弹出窗口的按钮)

@Ajax.ActionLink("Search current form", "SearchAction", new { @id = "SearchBtn" }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "result", InsertionMode = InsertionMode.Replace, OnSuccess = "openPopup" }, new { @class ="btn btn-primary"})<br />
<div id="result" style="display:none"></div>
<script type="text/javascript">
    $(document).ready(function () {
        $("#result").dialog({
            autoOpen: false,
            title: 'Search Window',
            resizable:0,
            width: 1000,
            height: 700,
            modal: true
        });
    });
    function openPopup() {
        $("#result").dialog("open");
    }
</script>

SearchForm视图 (作为部分视图实现)

@using (Html.BeginForm("SearchAction", "ViewModel", FormMethod.Post, new { @id = "searchform" }))
{
    //some form elements

    <div class="text-center">
        <input type="submit" value="Go" class="btn btn-primary"/>
    </div>
}


<div class="alert-danger">@ViewBag.emptyResult</div>

@if (Model != null)
{
    //display the search results 
}

现在要保留弹出窗口,我必须以与“表单视图”相同的方式将 Go 按钮绑定到ajax操作。同样,通过阅读此How to pass formcollection using ajax call to an action?,我知道Ajax操作将JSON数据发布到控制器中,而不是FormCollection可以轻松访问的键值对。因此,我的问题是如何在搜索表单中实现提交按钮(Ajax.Actionlink),以便它使用FormCollection将数据发布到控制器中并保留弹出窗口。

1 个答案:

答案 0 :(得分:0)

原来,我只需要在搜索弹出窗口中为结果表定义一个占位符即可。

<div id="showData" class="text-center table table-bordered bg-light"></div>

现在通过Ajax调用获取搜索结果

function GetSearchResult() {
        var searchParams = [];
        //get search queries from textbox ids

        $.ajax({
            type: 'POST',
            dataType: "json",
            traditional: true,
            data: {
                s: searchParams
            },
            url: "/{controller name} /{action}",
            success: function (result) {
                var col = [];
                if (isJson(result)) {
                    var sR = JSON.parse(result);
                    //create a html table using javascript and fill it which the result you got
                var divContainer = document.getElementById("showData");
                divContainer.innerHTML = "";
                divContainer.appendChild(table);  //table is what you created dynamically using javascript
                }
                else {
                    alert("No results found, Please try again");    
                }

            }
        });
    }

在您的控制器中添加此操作

[HttpPost]
public JsonResult AjaxMethod(string value, string Id)
{
     var updatedList = GetSearchResults(); //get search result from your repository
     return Json(updatedList);
}

就创建html表而言,javascript是this帮了我很多忙!