2012-04-11 132 views
1

這裏是我的簡單的類時綁定一個複選框的模型:提交表單

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using XXX.Domain; 

namespace XXX.WebUI.Models 
{ 
    public class AccountRegisterModel 
    { 
     ..snip.. 

     [Required(ErrorMessage = "You must agree to our terms of use.")] 
     public bool AcceptedTerms { get; set; } 

     ..snip.. 
    } 
} 

而我的觀點:

<div class="terms"> 
    <input type="checkbox" name="AcceptedTerms" value="AcceptedTerms" /> 
    <img class="sim" src="@Url.Content("~/Public/images/unchecked.gif")" alt="accept the terms" /> 
    <p>I accept the <span class="legalize">Terms of Service &amp; Privacy Policy</span> and wish to continue</p> 
</div> 

的視圖開始時複選框未選中,並使用一些JavaScript代碼我使用圖像創建一個時髦的複選框,並在幕後更新複選框,以便將正確的值回傳。

$('.terms input[type="checkbox"]').prop("checked", true); 

爲了調試的目的我已經添加了display:block規則「隱藏」 實際複選框是否已選中實際上是被選中當我點擊的形象和我可以證實,這是事實。

而且,使用Firebug,這裏是當我點擊圖片,圖片顯示的HTML和複選框被選中:

<input type="checkbox" name="AcceptedTerms" value="AcceptedTerms"> 

當窗體發佈,AcceptedTerms的值保持假時,如果該值沒有被髮回到我的服務器。也許HTML缺少一個我不知道的屬性。

任何想法或建議嗎?

+0

什麼形式?你如何發佈它? jQuery $ .ajax或類似的東西? – 2012-04-11 01:13:09

+0

我沒有發佈HTML表單,因爲它不相關。對於那個POSTS數據來說很簡單,沒有什麼與$ .ajax或者什麼。 :)如果你需要看到它,讓我知道,但它沒有什麼不尋常的。 – 2012-04-11 01:15:56

回答

0
<input type="checkbox" name="AcceptedTerms" value="AcceptedTerms" /> 

應改爲

<input type="checkbox" name="AcceptedTerms" value="true" /> 

值需要爲真不AcceptedTerms。

如果使用@ Html.CheckBoxFor(X => x.AcceptedTerms)

,你會看到該值設置爲true。

0

保持您需要將您的複選框綁定到視圖模型的值。我想它是這樣的:

@Html.CheckBoxFor(x => x.AcceptedTerms) 

當你的表格被張貼時,它應該有複選框的值,即。如果它被檢查(true)或不(false)。