在设置httpmethod发布时,Ajax.Actionlink转发到Get方法

时间:2014-01-13 15:53:30

标签: c# ajax asp.net-mvc partial-views

Controller的get和post方法

 [HttpGet]
    public ActionResult Index()
    {

        SoSession.Authenticate("pierre", "pierre");
        return View();
    }

    [HttpPost]
    public ActionResult Index(CompanySearch model)
    {

        return RedirectToAction("Companies",new{searchString=model.SearchString});

    }

在视图中

@using (Html.BeginForm("Index", "Company"))
{
    <div class="input-block-level">
         @Html.TextBoxFor(m => m.SearchString)
         @Ajax.ActionLink(
             "Submit",
             "Index", 
             new{}, 
             new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "partialDiv" }) 
    </div>


}

<div id="partialDiv"></div>

问题 每当用户点击提交链接时,我会转发到get方法而不是post方法。如何将呼叫转发到我的控制器的post方法?

3 个答案:

答案 0 :(得分:2)

确保正确加载到视图中的unobutrusive ajax库文件(以及它的依赖项(jQuery))。如果您没有将此文件加载到您的页面,单击Ajax.ActionLink帮助程序方法生成的链接将执行GET请求,而不是您期望的异步POST

<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

答案 1 :(得分:2)

听起来你正试图使用​​ajax形式:

@using Ajax.BeginForm("Submit", "Company", FormMethod.Post, new AjaxOptions { UpdateTargetId = "partialDiv", InsertionMode = InsertionMode.Replace}) {
    @Html.TextBoxFor(m => m.SearchString)
}

如果包含应该有效的ajax js库。

答案 2 :(得分:0)

您也可以使用JQuery进行部分加载,尽管控制器会返回部分加载。我同意mayabelle Ajax.BeginForm()是另一条路线。

[HttpGet]
public ActionResult Companies(string searchString)
{
    return this.PartialView("MyView", MyObject)
}

在cshtml javascript里面:

var searchString = $("#SearchString").val();
$("#partialDiv").load('@Url.Content("~/Home/Companies/")' + searchString, function(){ DoSomething(); });