2016-05-16 181 views
0

我使用的.Net MVC5,我試圖創建與編輯鏈接(或按鈕)將發佈(所以我不能使用ActionLink的)整個索引視圖在視圖中呈現的實體列表中的模型項目實體。我該怎麼做?MVC5傳遞模型項目從視圖到控制器

我的代碼(到目前爲止)低於

@model IEnumerable<Projname.Models.MyEntity> 
<!DOCTYPE html> 

<html> 
<head> 
    <meta name="viewport" content="width=device-width" /> 
    <title>Index</title> 
</head> 
<body> 
    <p> 
     @Html.ActionLink("Create New", "Create") 
    </p> 
    <table class="table"> 
     <tr> 

      <th> 
       @Html.DisplayNameFor(model => model.Name) 
      </th> 
      <th>Hello there</th> 
      <th>life is good</th> 
      </tr> 

    @foreach (var item in Model) { 
     <tr> 

      <td> 
       @Html.DisplayFor(modelItem => item.Name) 
      </td> 
      <td> 

       @using (Html.BeginForm("Edit", "Edit", FormMethod.Post)) 
       { 
        @Html.Hidden(mytem => item); 

      <input type="submit" value="Edit" class="btn btn-default" /> 
       } 
      </td> 
      <td>     
       @Html.ActionLink("Details", "Details", new { id = item.PrimeKey }) | 
       @Html.ActionLink("Delete", "Delete", new { id = item.PrimeKey }) 
      </td> 
      </tr> 
    } 

    </table> 
</body> 
</html> 

我假設有一個更好的方式來做到這一點,而不是爲每個實體的屬性創建一個隱藏字段。

+1

通myItem和剛ID /主鍵再從數據庫中檢索項當你將它傳遞給你的編輯視圖。 – AWinkle

+0

爲什麼通過整個模型,只是標識會做 – scottdavidwalker

+1

@AWinkle通常我會做到這一點,但因爲我使用Azure的表,只有指定查詢的行鍵(主鍵)會導致不良的全表掃描http://stackoverflow.com/questions/19715885/azure-tables-query-by-rowkey-as-condition。所以我儘量避免它。 – JOW

回答

0

你需要把你想編輯或更改成形式

<form class="form-horizontal" action="GetItemsFromView" method="post"> 
    <input type="text" name="EditedModelItem"> 
</form> 

之後,您可以在您的控制器調用任何修改的項目中的項目,通過 串保持=的Request.Form [「EditedModelItem」] ;在GetItemsFromView方法中的 。

0

總結一切:

@using (Html.BeginForm("Edit", "Edit", FormMethod.Post)) 
{     
} 

然後:

public ActionResult Edit(Model model) 
{ 
     if (ModelState.IsValid) 
     { 
     } 
} 

或者:

public ActionResult Edit(FormCollection formCollection) 
{ 
} 
相關問題