在视图中使用ajax.beginform但控制器无法识别为ajax请求

时间:2017-06-29 14:47:51

标签: asp.net-mvc

这是使用vb.net开发的na asp.net mvc 5应用程序 我在视图中使用Ajax.beginform,但是当控制器返回请求时,它不会被识别为ajax请求。 以下是视图的代码

<div Class="modal-dialog">
    <div Class="modal-content">
        <div Class="modal-header">
            <Button type="button" Class="close" data-dismiss="modal" aria-hidden="true"></Button>
            <h4 Class="modal-title">Edit Nome</h4>
        </div>
        @Using (Ajax.BeginForm("Edit", "Nomes", Nothing,
                                                New AjaxOptions With {.HttpMethod = "POST", .OnSuccess = "UpdateSuccess"},
                                                New With {.Class = "form-horizontal", .role = "form"}))

    @Html.AntiForgeryToken()
            @<div Class="modal-body">
...........
                    <div class="col-md-offset-2 col-md-20">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <input type="submit" class="btn btn-primary" value="Save Changes" />
                    </div>
                </div>
            </div>
        End using
    </div>
</div>

她是控制器的代码

<HttpPost>
        <ValidateAntiForgeryToken()>
        Public Async Function Edit(modelNome As NomeVM) As Task(Of ActionResult)

            If Not ModelState.IsValid Then
                Response.StatusCode = CInt(HttpStatusCode.BadRequest)
                Return View(If(Request.IsAjaxRequest(), "Edit", "Edit"), modelNome)
            End If

            Dim nome As Nome = MaptoModel(modelNome)

            dbContext.Nome.Attach(nome)
            dbContext.Entry(nome).State = EntityState.Modified
            Dim task = dbContext.SaveChangesAsync()
            Await task

            If task.Exception IsNot Nothing Then
                ModelState.AddModelError("", "Unable to update the Nome")
                Response.StatusCode = CInt(HttpStatusCode.BadRequest)
                Return View(If(Request.IsAjaxRequest(), "Edit", "Edit"), modelNome)
            End If

            If Request.IsAjaxRequest() Then
                Return Content("success")
            End If

            Return RedirectToAction("Index")

        End Function

1 个答案:

答案 0 :(得分:0)

您可能缺少jquery.unobtrusive-ajax.min.js。你不能使用cdn,而是去管理nuget。安装jquery.unobtrusive-ajax并引用它。

归功于Using Ajax.BeginForm with ASP.NET MVC 3 Razor

这是一个例子

查看:

Imports System.ComponentModel.DataAnnotations

Public Class MyViewModel
    Public Property Foo() As String
End Class

Public Class HomeController
    Inherits System.Web.Mvc.Controller

    <HttpPost>
    Function Index(ByVal myViewModel As MyViewModel) As ActionResult
        Return Content("Thanks", "text/html")
    End Function

    Function Index() As ActionResult
        Return View(New MyViewModel())
    End Function

控制器/型号:

{{1}}