2013-04-09 84 views
0

您可以在一個請求中使用與asp.net MVC4相同的模型作爲參數兩次嗎?在一個請求中使用同一模型兩次

public ActionResult Search(SearchModel model) 
{ 
    SearchResults resultsModel = new SearchResults(); 

    resultsModel.Results = new List<string>(); 
    resultsModel.Results.Add("posted value : " + model.Phrase); 

    return View("SearchResults", resultsModel); 
} 

[ChildActionOnly] 
public ActionResult SearchPartial(SearchModel model) 
{ 
    model.Phrase = "changed in search partial"; 

    return PartialView("_SearchPartial", model); 
} 

我做一個@Html.Action("SearchPartial")_Layout,cshtml但是不管我發佈的時候任何頁面調用@HtmlAction第二方法上面的第一種方法是什麼模型從來沒有最終被送往客戶端的字符串「在搜索部分更改」。

它就像我不能使用相同的模型兩次,如果在同一個請求中調用兩個動作。這真的很討厭....

我甚至改變了第一種方法只使用1參數,但它總是回來與任何張貼,而不是我把它設置爲服務器端!

+0

我沒有看到在同一個請求中調用兩個動作。您是否期望在搜索操作中定義的模型在頁面上執行時獲取SearchPartial操作中設置的詞組? – 2013-04-09 19:28:41

回答

0

這應該很好。我剛剛測試了以下:

控制器:

public ActionResult Search(SearchModel model) 
{ 
    SearchResults resultsModel = new SearchResults(); 

    resultsModel.Results = new List<string>(); 
    resultsModel.Results.Add("posted value : " + model.Phrase); 

    return View("SearchResults", resultsModel); 
} 

[ChildActionOnly] 
public ActionResult SearchPartial(SearchModel model) 
{ 
    model.Phrase = "changed in search partial"; 

    return PartialView("_SearchPartial", model); 
} 

型號:

public class SearchModel 
{ 
    public string Phrase { get; set; } 
} 

public class SearchResults 
{ 
    public List<string> Results { get; set; } 
} 

SearchResults.cshtml:

@model SearchResults 

@foreach (var item in Model.Results) { 
    <div>@item</div> 
} 

_SearchPartial.cshtml:

@model SearchModel 
<strong>Search Phrase:</strong> @Model.Phrase 

_Layout.cshtml:

<!DOCTYPE html> 
<html lang="en"> 
    <body> 
     <div> 
      <h2>Partial Contents</h2> 
      @Html.Action("SearchPartial", "Home") 
     </div> 
     <div> 
      <h2>Body Contents</h2> 
      @RenderBody() 
     </div> 
    </body> 
</html> 

結果(與查詢字符串: 「這句=測試?」):

<!DOCTYPE html> 
<html lang="en"> 
    <body> 
     <div> 
      <h2>Partial Contents</h2> 
      <strong>Search Phrase:</strong> changed in search partial 
     </div> 
     <div> 
      <h2>Body Contents</h2> 
      <div>posted value : Test</div> 
     </div> 
    </body> 
</html> 
0

當您使用@Html.Action("SearchPartial")撥打電話時,它將其視爲對名爲SearchPartial的操作的全新請求,它不會隱式地繼承父操作中的任何模型或TempData。你必須自己做。

編輯:從什麼克里斯在下面留言已經提到的,ChildAction但會嘗試綁定它的使用會傳遞給家長行動的 參數輸入模型。

@Html.Action("SearchPartial", new {model = Model}) 

然而當過我已經在過去做到了這一點我通過在原始數據不完整的對象,所以你可能要做到這一點,而不是。

@Html.Action("SearchPartial", new {phrase = Model.Phrase, page = Model.Page, perPage = Model.PerPage})` 

注意:我只是猜測你的SearchModel ViewModel的屬性。

+0

這不完全正確。是的,模型不是從父動作傳遞的,而是使用原始的請求參數。所以在這種情況下,由於父動作和子動作都接受'SearchModel',它應該可以在@ Html.Action(「SearchPartial」)下正常工作。 ChildAction不會修改父視圖的模型。 – 2013-04-09 21:29:57

+0

啊,是的,我明白你的意思了。我沒有注意到ChildAction中的那條線試圖修改輸入模型。 – 2013-04-09 22:40:09

相關問題