2012-03-13 120 views
1

首先,對不起我的英語不好。如何通過ajax.BeginForm更改內容?

我想當一個人點擊按鈕「Page1」,控制器返回「Page1」的renderpartial和「page2」和「allPage」的相同的東西。

我的看法是:

@{ 
ViewBag.Title = "Title"; 
} 
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script> 
<h2>Title</h2> 

@using (Ajax.BeginForm("NameAction", //controller action name 
"NameController", //controller name 
new AjaxOptions //ajax options that tell mvc how to perform the replacement 
{ 
UpdateTargetId = "ViewPage", //id of div to update 
HttpMethod = "Post" //how to call the controller action 
}, new { id = "FormName" })) 
{ 
<input type="submit" id="btn" value="p1" id="p1"/> 
<input type="submit" id="btn" value="p2" id="p2"/> 
<input type="submit" id="btn" value="AllPage" id="AllPage"/> 
<div id="ViewPage"> 
    //render partial view 
</div>   
} 

我的控制器:

public class NameController : Controller 
{ 
    [HttpPost] 
    public ActionResult NameAction(String btn) 
    { 
     if (Request.IsAjaxRequest()) 
     if(btn="p1") 
     return PartialView("p1"); 
     if(btn="2") 
     return PartialView("p2"); 
     if(btn="3") 
     return PartialView("p3"); 


     return View(); 
    } 
} 

Request.isAjaxRequest總是等於false和partialview不更新的股利,但刪除所有頁面

感謝你的幫助。

+0

MVC2或MVC3?請清理你問題的標籤。 – ThiefMaster 2012-03-13 16:32:00

+0

@ThiefMaster,我已經移除了'asp.net-mvc-2'標籤,它不能與'razor'一起使用。 – 2012-03-13 16:36:58

+0

對不起,感謝您對Darin Dimitrov的更正。這是工作中,因爲,與我的「字符串btn」的解決方案不是空的,但ajax選項不起作用:(如果我在我的控制器測試isAjaxRequest等於永遠爲false。partialview擦除我的所有頁面,而不是更新div:s – Zoners 2012-03-13 16:54:55

回答

1

給你的提交按鈕的名稱:

<input type="submit" name="btn" value="page1" id="Page1"/> 
<input type="submit" name="btn" value="Page2" id="Page2"/> 
<input type="submit" name="btn" value="AllPage" id="AllPage"/> 

然後:

[HttpPost] 
public ActionResult NameAction(string btn) 
{ 
    if (btn == "page1") 
    { 
     // the page1 button was clicked 
    } 
    else if (btn == "page2") 
    { 
     // the page2 button was clicked 
    } 
    else if (btn == "AllPage") 
    { 
     // the AllPage button was clicked 
    } 

    ... 
} 

,如果你不想依賴按鈕的實際標籤上:

<button type="submit" name="btn" value="p1" id="Page1">Show page 1</button> 
<button type="submit" name="btn" value="p2" id="Page2">Show page 2</button> 
<button type="submit" name="btn" value="all" id="AllPage">Show all pages</button> 

並在控制器中可以檢查該值。


UPDATE:

請確保您有包括jquery.unobtrusive-ajax腳本到您的網頁,以便Ajax.BeginForm工作,併發送一個AJAX請求:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>