2016-04-21 101 views
0

我想用Ajax.BeginForm我Asp.Net MVC項目和下面是a.cshtml文件Ajax.BeginForm犯規提交表單值

@using (Ajax.BeginForm("ActionName", "ControllerName", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "DivName" })) 
{ 
    <input type="hidden" name="posted" id="posted" value="5" /> 
    <input type="submit" id="sBtn" value="Submit" /> 
} 

的代碼,我的行爲是下面的,但我不能獲取操作中發佈的參數。爲什麼?

[HttpPost] 
public ActionResult ActionName(string posted) 
{ 

    //posted is null why? 
    .... 
} 

我已經添加

<add key="UnobtrusiveJavaScriptEnabled" value="true" /> 

到WEB.CONFIG

"~/Scripts/jquery.unobtrusive-ajax.min.js" 

捆綁

如果我使用Html.BeginForm代替Ajax.BeginForm在a.cshtml上工作正常。

回答

0

嘗試確保您發佈的方法來裝飾與[HttpPost]屬性,這將確保它可以接收POST請求:

[HttpPost] 
public ActionResult ActionName(string posted) 
{ 

} 

除了顯示你的代碼像預期它應該只是工作。下面的例子應該在行動證明這兩種情況下:

HomeController.cs

using System; 
using System.Web.Mvc; 
using System.Collections.Generic; 

namespace PostingExample 
{ 
    public class HomeController : Controller 
    { 
     [HttpGet] 
     public ActionResult Index() 
     { 
      return View(); 
     } 

     [HttpPost] 
     public ActionResult Index(string posted, bool isAjax = false) 
     { 
      return Content(String.Format("{0} was posted. {1}",posted, isAjax ? "(via AJAX)" : "")); 
     } 
    } 
} 

Index.cshtml

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <title>Post Testing</title> 
</head> 
<body> 
    <h2>Normal Form</h2> 
    @using (Html.BeginForm("Index", "Home")) 
    { 
     <input type="hidden" name="posted" id="posted" value="5" /> 
     <input type="submit" id="sBtn" value="Submit" /> 
    } 
    <h2>AJAX Form</h2> 
    @using (Ajax.BeginForm("Index", "Home", new AjaxOptions() { HttpMethod = "Post", UpdateTargetId = "DivName" })) 
    { 
     <input type="hidden" name="posted" id="posted" value="5" /> 
     <input type='submit'> 
    } 

    <!-- jQuery and related scripts --> 
    <script src="https://code.jquery.com/jquery-2.1.4.js"></script> 
    <script src='http://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js' /> 
</body> 
</html> 
+0

Html.BeginForm正在工作,但Ajax.BeginForm不起作用 – brtb

+0

我嘗試使用[與您自己的結構儘可能相似的示例](https://gist.github.com/Rionmonster/2a62521a07335bb56d20dc897ef0ba94),它起作用如預期。你可以嘗試確保所有信息與提供的示例相同嗎? –

+0

您可能希望確保您的'jquery.unobtrusive-ajax.min.js'文件已正確加載,並且您的瀏覽器中的開發工具(F12)中沒有任何404錯誤與之相關。 –

0

與Ajax.BeginForm,在你的控制器,你需要申請[「您輸入的名稱」]如下:

public ActionResult ActionName() 
{ 
    string Posted = Request["posted"]; 

    //Some more code 
}