2016-09-23 72 views
1

我開始幾天MVC工作,有一個問題出學習的途徑很多在MVC如何動態地將提交按鈕的值傳遞給mvc?

我有以表格形式顯示員工列表頁控制器和視圖之間進行通信的。

模型是Employee Model

IEnumerable類型的,具有三個按鈕它們EditCreateDeleteDetails

要求:
我使用的按鈕,使所有應HTTP POST請求類型的,因爲我不希望用戶使用的URL請求直接訪問它們。

這裏是我的視圖代碼:

@using (Html.BeginForm()) 
{ 
    <p> 
     <input type="submit" name="CreateView" value="Create New(Post)" formaction="CreateView" formmethod="post" /> 
    </p> 
    <table class="table"> 
     <tr> 
      -------Headings of table------- 
     </tr> 
     @foreach (var item in Model) 
     { 
     <tr> 
      <td>@Html.DisplayFor(modelItem => item.EmployeeName)</td> 
      <td>@Html.DisplayFor(modelItem => item.EmployeeGender)</td> 
      <td>@Html.DisplayFor(modelItem => item.EmployeeCity)</td> 
      <td>@Html.DisplayFor(modelItem => item.DepartmentId)</td> 
      <td>@Html.DisplayFor(modelItem => item.EmployeeDateOfBirth)</td> 
      <td> 
       <input type="submit" name="EditView" value="Edit(Post)" formaction="Edit" formmethod="post" /> | 
       <input type="submit" name="DetailsView" value="Details(Post)" formaction="Details" formmethod="post" /> | 
       <input type="submit" value="Delete(Post)" onclick="return confirm('Are you sure you want to delete record with EmployeeId = @item.EmployeeId')" /> 
      </td> 
     </tr> 
     } 
    </table> 
} 

這裏刪除按鈕作品,因爲我並不需要的員工的ID。 但對於編輯,刪除和詳細信息查看等其他操作,我需要將員工ID傳遞給控制器​​。但是,如何使用提交按鈕將ID傳遞給控制器​​。

在GET請求類型我用來傳遞這樣的:

@Html.ActionLink("Details", "Details", new { id = item.EmployeeId }) 

對於單提交按鈕,我用來傳遞這樣

@using (Html.BeginForm("Details", "BusinessLayer", FormMethod.Post, new { id = item.EmployeeId })) 

數據中的任何一個可以告訴我的方法,我可以休耕來實現這一目標?

+0

單個表單內的多次提交可能是一個壞主意。你可以使用按鈕,而在JavaScript的幫助下,你可以提交它。 –

+0

@PrashantMohite,OP想重定向,所以Ajax不會工作。 –

+0

只需爲集合中的每個操作和每個項目創建一個表單 - 「@ Html.BeginForm(」Edit「,」yourControllerName,new {id = item.EmployeeId})){}'等 –

回答

6

您可以有3個單獨的窗體標籤,每個按鈕一個。只要確保你在表單中有一個你想傳遞的數據的輸入字段。例如,如果您的操作方法使用名爲EmployeeId的參數接受EmployeeId,則應該在輸入隱藏字段中使用表單中的相同內容。

@model IEnumerable<Employee> 
<table> 
@foreach(var item in Model) 
{ 
    <tr> 
     <td>@item.EmployeeName</td> 
     <td>@item.EmployeeGender</td> 
     <td>@item.EmployeeCity</td> 
     <td>@item.EmployeeDateOfBirth</td> 
     <td> 
     @using(Html.BeginForm("Details","YourControllerName")) 
     { 
      <input type="hidden" name="EmployeeId" value="@item.EmployeeId" /> 
      <input type="submit" value="Details" /> 
     } 
     @using(Html.BeginForm("Edit","YourControllerName")) 
     { 
      <input type="hidden" name="EmployeeId" value="@item.EmployeeId" /> 
      <input type="submit" value="Edit" /> 
     } 
     @using(Html.BeginForm("Delete","YourControllerName")) 
     { 
      <input type="hidden" name="EmployeeId" value="@item.EmployeeId" /> 
      <input type="submit" value="Delete" /> 
     } 
     </td> 
    </tr> 

} 

還記得,嵌套窗體是無效的HTML。所以請確保你沒有這些。

+0

這是一個工程我。有人說在單一表單中使用多個提交是不好主意?它是否有效?如果有的話,任何機構都可以解釋? –