如何在不更改当前页面的情况下执行操作?

时间:2019-07-13 08:52:44

标签: jquery html asp.net json ajax

我想在不更改当前页面的情况下将所选项目添加到控制器中的会话中。

<form>
@Html.HiddenFor(m => m.Id)
    @Html.HiddenFor(m => m.Title)
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">@Model.Title</h4>
        </div>
        <div class="modal-body">
            <ul class=" check-list" id="GroupFeatures">
                @{

                    for (int i = 0; i < Model.GroupFeatures.Count; i++)
                    {
                        @Html.HiddenFor(m => m.GroupFeatures[i].Id)
                        <li><span> @Model.GroupFeatures[i].Title </span> @Html.DropDownListFor(m => m.GroupFeatures[i].Value, new SelectList(Model.GroupFeatures[i].Features, "Id", "Title"), new { @class = "form-control" })</li>
                    }
                }
            </ul>
        </div>
        <div class="modal-footer">
            <button id="submit" class="btn btn-default "  >ثبت</button>

        </div>
    </div>
</form>

在脚本中。

$(document).on('click', '#submit', function () {
var data = $('form').serialize();

$.getJSON("/store/MakeMyFavorite", data, function (data) {
    //check your data here what it is returning
    if ($.trim(data) == "favorite") {
        alert('s');
    }
});

});

和控制器中。

public JsonResult MakeMyFavorite(ProductFeatureViewModel model)
    {
       string result = "favorite";
        return this.Json(result, JsonRequestBehavior.AllowGet);
    }

但将网址更改为/Store?__RequestVerificationToken=526Wd9OvHI89rwGrRuCgzgDhAGloEuZkOLSdoQFTELZcLQliMMWlc8AeMn3DS4Sfy5-k8xr2tavkno-2aNBjIyJXR4c8T9PmNSs-KlUNITo1&Id=1&Title

1 个答案:

答案 0 :(得分:0)

提交表单后,您需要停止表单的正常行为,即将表单完整回发到服务器。

为此,您可以使用浏览器引发的事件的preventDefault()函数:

$(document).on('click', '#submit', function (event) {
    event.preventDefault();
    //...etc