2013-03-13 39 views
0

我有一些問題從表單中獲取複選框的值。我可能做錯了什麼,但我無法想象出我的一生。在表單中顯示基於複選框的表單

在我看來,代碼如下所示:

@using (Html.BeginForm("DisplayEmpPhotos", "Home", null, FormMethod.Post, new { id = "GetEmpNumbers" })) 
{ 


<div id = "empForm"> 
    <br/> 
    Event Name:<input type ="text" name="EventName"/> 
    <br/> 
    Event Dates:<input type ="text" name="EventDates"/> 
    <br/> 
    <br/> 
    <br/> 
    Enter Employee IDs: 
    <br/> 
    Consultant: <input type="checkbox" name="consultant" value="include" checked="checked" /> 
    <br/> 
} 

有跡象表明,此複選框下面幾個文本框輸入,但他們很好地工作。

在我的控制器中的代碼看起來是這樣的:

public ActionResult DisplayEmpPhotos(string EventName, string EventDates, string consultant) 
{ 
    ViewData["EventName"] = EventName; 
    ViewData["EventDates"] = EventDates; 
    if(consultant == "include") 
    { 
     ViewData["Image"] = "<img src ='imgsrc' alt='First&nbsp;Last' class='nopad'/>"; 
     ViewData["Name"] = "First&nbsp;Last"; 
     ViewData["Deparment"] = "C"; 
     ViewData["Title"] = "Consultant"; 
    } 

視圖有這它:

<td class="smalltext"> 
     @ViewData["Image"] 
     <p> 
     @ViewData["Name"] 
     </p> 
     @ViewData["Department"] 
     <br/> 
     @ViewData["Title"] 
</td> 

我的想法是,如果選中該複選框,它的價值傳遞我應該能夠將Viewdata分配給這些信息並將其顯示在視圖中。我知道像這樣的硬編碼價值觀是不好的做法,但是對於我所做的這是可以接受的。任何幫助我做錯了讚賞。

回答

2

當你的Controller應該是「顧問」時,你的控制器方法中有名爲「checkbox」的變量,你真的應該使用Html CheckBox幫手。

所以在查看:

Consultant: @Html.Checkbox("consultant", true) 

和Controller,改變值是一個布爾值:

public ActionResult DisplayEmpPhotos(string EventName, string EventDates, bool consultant) 
{ 
    ViewData["EventName"] = EventName; 
    ViewData["EventDates"] = EventDates; 

    if(consultant) 
    { 
     ViewData["Image"] = "<img src ='imgsrc' alt='First&nbsp;Last' class='nopad'/>"; 
     ViewData["Name"] = "First&nbsp;Last"; 
     ViewData["Deparment"] = "C"; 
     ViewData["Title"] = "Consultant"; 
    } 
} 

讓我知道這並不爲你工作。

+0

謝謝,這很有道理。然而,我認爲這些數據仍然沒有顯示出來。我將使用該代碼編輯該問題。 – 2013-03-13 16:53:51

+0

作了一些更新。 – 2013-03-13 20:58:11

0

如果在您的ActionResult您從string checkbox更改爲string consultant

有些時候確實MVC對我,當我更改輸入的名字正是我在我的ActionResult宣佈他們,他們的工作。

相關問題