2011-04-03 33 views

回答

1

給每個按鈕的名稱,像這樣(請注意,它們都是「提交」按鈕)::

<input type="submit" name="buttonYes" value="Yes" /> 
<input type="submit" name="buttonNo" value="No" /> 

然後,在你的控制,捕獲參數用於兩個按鈕像這樣的名字:

public ActionResult Index(string buttonYes, string buttonNo) { ... } 

然後,您可以通過檢查以查看哪個按鈕被按下,以查看哪兩個參數不爲空;它壓成一個具有等於按鈕的「值」屬性的值,另外一個將是無效的:

if (buttonYes != null) 
{ 
    // Then the yes button was preseed 
} 
else if (buttonNo != null) 
{ 
    // Then the no button was pressed 
} 
else 
{ 
    // Neither button was used to submit the form 
    // and we got here some other way 
} 

這部作品的原因是因爲web瀏覽器發送的信息提交按鈕是作爲HTTP發佈到Web服務器的一部分的按鈕。未按下的按鈕不會與帖子一起發送,因此參數將爲空。

有很多方法可以改寫和優化這個,但這是它的本質,並顯示了工作中的基本原理 - 你可以從那裏玩它。

+0

感謝您的解決方案,但我仍然有問題,我只想讓用戶只投一個候選人。因此每個按鈕值都是具有不同ID的「投票」。 – Mike 2011-04-03 14:08:17

+0

這與上述工作 - 只需將每個按鈕的值更改爲「投票」。上述解決方案中的值並不重要;這是按鈕的ID必須不同,就像你所描述的那樣。而這個解決方案只允許一個候選人投一票。試試看看。您還可以將解決方案擴展到未知數量的候選人/投票按鈕,但只需檢查FormValues集合中的值而不是控制器本身的參數 - 這樣您就不必知道提前期望的候選人。 – 2011-04-03 14:12:43

+0

更正:這應該說使用「FormCollection」,如下所示:public ActionResult Index(FormCollection fc) – 2011-04-03 14:26:19

1

我不會使用按鈕值,我會設置它,以便用於執行帖子的網址對投票本身進行編碼。你可以通過幾種方法做到這一點。

使用鏈接

<div class="left"> 
    <img src="/images/candidate/@Model.Candidates[0].ID" alt="@Model.Candidates[0].Name" /> 
    @Html.ActionLink("Vote for " + Model.Candidates[0].Name, "count", "vote") 
</div> 
<div class="right"> 
    <img src="/images/candidate/@Model.Candidates[1].ID" alt="@Model.Candidates[1].Name" /> 
    @Html.ActionLink("Vote for " + Model.Candidates[1].Name, "count", "vote") 
</div> 

使用單獨的形式

<div class="left"> 
    @using (Html.BeginForm("count", "vote", new { id = Model.Candidates[0].ID })) 
    { 
     <img src="/images/candidate/@Model.Candidates[0].ID" alt="@Model.Candidates[0].Name" /> 
     <input type="submit" value="Vote" /> 
    } 
</div> 
<div class="right"> 
    @using (Html.BeginForm("count", "vote", new { id = Model.Candidates[1].ID })) 
    { 
     <img src="/images/candidate/@Model.Candidates[1].ID" alt="@Model.Candidates[1].Name" /> 
     <input type="submit" value="Vote" /> 
    } 
</div> 

上述任何一種可以適應與AJAX來正常工作。請注意,如果您在意,您需要建立一些機制來檢測投票欺詐,例如,爲網址添加一次性隨機數,以驗證它不會被多次使用;跟蹤用戶投票的次數,如果他們被認證等。