通过 jQuery 使用 ASP.NET MVC 提交表单并接收值

Submitting a form with ASP.NET MVC via jQuery and receiving a value

我正在开发一个 ASP.NET MVC 项目,在该项目中,提交表单后,模型会在数据库中创建一条新记录并将记录 ID 发送回表单(然后将对其进行操作在一些额外的 JavaScript 代码中)。

我正在使用 Telerik Kendo window 控件,所以我的想法是用户将单击 Kendo 弹出窗口中的提交按钮 window 并将启动事件链。收到值后,Kendo 弹出窗口 window 将关闭。

我一直在关注此线程中的示例:PartialView with a form in a kendo window

就提交表单而言,此行为正常。此代码不从控制器接收任何值。在视图中:

<input type="button" value="Create" class="btn btn-default" onclick="formSubmit()"/>

后来...

<script>
    function formSubmit() {
    if (!inIframe()) {
        // We are a parent window
        $('form').submit();
    }
    else {
        // We are a pop-up window
        $('form').submit();
        parent.$('#window').data('kendoWindow').close();
    }
    }
</script>

@(Html.Kendo().Window()
    .Name("window")
    .Title("Attached Report")
    .Content("Loading...")
    .Actions(actions => actions.Close())
    .Iframe(true)
    .Height(700)
    .Width(1000)
    .Modal(true)
    .AutoFocus(true)
    .Visible(false)
)

在控制器中:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(VMMyViewModel viewModel)
{
    // Code omitted...basically, we save to the database
    db.SaveChanges();

    if (viewModel.IsInPopupWindow)
    {
     return null; // We return null to help us exit out of the popup window.
    }
    else
    {
    return RedirectToAction("Index"); // Since we're in the main window, go back to the index after submitting.
    }
}

我想获取我们刚刚保存到数据库中的记录的记录 ID,并以某种方式将其反馈给 jQuery 调用代码。我能够在控制器中发回记录 ID 的实际值,但它将作为包含记录 ID 的网页返回...

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(VMMyViewModel viewModel)
{
    // Code omitted...basically, we save stuff
    db.SaveChanges();

    if (viewModel.IsInPopupWindow)
    {
            return Content(reportHeader.Id.ToString());
    }
    else
    {
    return RedirectToAction("Index"); // Since we're in the main window, go back to the index after submitting.
    }
}

在 jQuery 方面,我似乎不应该使用 $('form').submit() 因为没有办法通过 [= 取回数据36=]机制。我尝试了其他几种方法(viewbags、jQuery 触发器、jQuery POST、Kendo window 控件上的关闭机制)但到目前为止我还没有无法将所有部分拼凑起来。

我怀疑我的处理方式完全错误。如有任何建议,我们将不胜感激!

在您的控制器中 return Json 而不是这样的内容:

if (viewModel.IsInPopupWindow)
{
        return Json(reportHeader.Id.ToString());
}

然后在你的 js 中,使用 $.post 这样

function formSubmit() {
    if (!inIframe()) {
        // We are a parent window
        // $('form').submit();
    $.post($('form').attr("action"), $("form").serialize(), function(id){
    // you got the id

   // rest omitted ...
})

基本上你使用 jquery 到 post 表格,这样你可以获得 post 的结果。然而,当你没有 return id 时你必须小心(在你当前的代码中有一个可能的重定向,我不会工作) - 也许 return 表明存在问题的东西