2015-10-02 44 views
0

List<ReviewGroupViewModel>類型的模型,其中ReviewGroupViewModel是:張貼到編輯控制器時,捕獲textarea的內容/視圖

public class ReviewGroupViewModel 
{ 
    public string Country { get; set; } 
    public List<Review> Reviews { get; set; } 
} 

在我Index.cshtml的看法,我通過這個模型中使用嵌套的for循環迭代和構建每個ReviewGroupViewModel的表格,按ReviewGroupViewModel.Country分組。我最終在每個Review對象的表格中排了一行。使用TextAreaFor HTML輔助顯示每行的Commentary領域,允許用戶輸入文本:

Index.cshtml

@using (Html.BeginForm("Save", "Review", FormMethod.Post)) 
{ 
    for (var i = 0; i < Model.Count; i++) 
    { 
     <h6>@Html.DisplayFor(m => m[i].Country)</h6> 
     <table class="table table-bordered table-condensed"> 
      <tr> 
       <th style="text-align: center"> 
        @Html.DisplayNameFor(m => m[i].Reviews[0].Commentary) 
       </th> 
       <th style="text-align: center"> 
        Actions 
       </th> 
      </tr> 
      @for (var j = 0; j < Model[i].Reviews.Count; j++) 
      { 
       <tr> 
        <td style="text-align: center"> 
         @Html.TextAreaFor(m => m[i].Reviews[j].Commentary) 
        </td> 
        <td style="text-align: center"> 
         @Html.ActionLink("Edit", "Edit", new { tempId = Model[i].Reviews[j].TempId }) | 
         @Html.ActionLink("Delete", "Delete", new { tempId = Model[i].Reviews[j].TempId }) 
        </td> 
       </tr> 
      } 
     </table> 
    } 
} 

這是由上點擊的提交形式爲界在頁面的其他地方點擊「保存」按鈕。

現在讓我們假設用戶在索引視圖中將一些文本鍵入到一個(或多個)textareas中,然後繼續點擊給定表格行的「操作」中的「編輯」。由於我只是將Id(類型:int)傳遞給我的Edit控制器方法,因此該文本丟失。問題是,在導航到其他視圖時,如何編輯/刪除這些輸入文本(對於Review對象和所有其他視圖)都不會丟失?

AFAIK,您不能直接將視圖中的複雜對象傳遞給控制器​​方法。你顯然也不能嵌套HTML表單。當然這是一種常見的情況,但我如何在代碼中處理它?

+0

但是,這是一個編輯窗體(您正在編輯'Commentary'屬性),那麼爲什麼你要導航到一個新的視圖來再次編輯它? –

回答

0

你的問題是ActionLink。它生成一個簡單的超鏈接。超鏈接將向服務器發送GET請求。而且你不能把複雜的對象放在GET請求的主體中。

你需要這樣做: Form with 2 submit buttons/actions

0

你的「for」循環中的代碼應該放到一個編輯模板。

@using (Html.BeginForm("Save", "Review", FormMethod.Post)) 
{ 
    for (var i = 0; i < Model.Count; i++) 
    { 
     @Html.EditorFor(m => Model[i], "MyTemplateName"); 
    } 
} 

創建一個名爲EditorTemplates內您查看文件夾中的文件夾,並創建一個視圖中調用MyTemplateName。在它裏面,通過將單個模型傳遞給視圖,您可以獲得迭代中每個單項的代碼。

MyTemplateName.cshtml

@model Review 

<h6>@Html.DisplayFor(m => m.Country)</h6> 
     <table class="table table-bordered table-condensed"> 
      <tr> 
       <th style="text-align: center"> 
        @Html.DisplayNameFor(m => m.Reviews[0].Commentary) 
       </th> 
       <th style="text-align: center"> 
        Actions 
       </th> 
      </tr> 
      @for (var j = 0; j < m.Reviews.Count; j++) 
      { 
       // Here you should have different editor template... see the pattern :) 
       @Html.EditorFor(m => m.Reviews[j], "MySecondTemplate") 
      } 
     </table> 

希望這些信息可以幫助你。

+0

感謝George,在MyTemplateName.cshtml中的'@model Review'被拋棄了。我認爲應該是'@model ReviewGroupViewModel'在我的情況? – illya

+0

在'MySecondTemplate'中,我將傳遞給控制器​​的是什麼?我仍然無法傳遞對象? – illya

相關問題