2013-12-23 92 views
0

我正在創建一個簡單的用戶註冊表單。用戶可以註冊爲公司或個人。以下是使用RadioButtonFor html helper的註冊表單的相關視圖。我已經定義在JavaScript中使用的id屬性:如何在mvc3中處理單擊或更改單選按鈕的事件

@model LayoutTest.ViewModels.ProjectUser 
    <script> 
    $(function() { 
    $("#Class_UserType").change(function(){ 
     var value = $(this).val(); 
     if (value == 1) { 
      $('#Person').hide(); 
     } 
     else if (value == 2) { 
      $('#Company').hide(); 
     } 
     }); 
    }); 
    </script> 
    @using (Html.BeginForm("Create", "Project", FormMethod.Post, new { enctype = "multipart/form-data" })) 
    { 
    @Html.ValidationSummary(true) 
    <fieldset> 
    <div class="new_row"> 
     <div class="editor-label"> 
      @Html.LabelFor(model => Model.UserType) 
     </div> 
     <div class="editor-field"> 
      <div class="editor-field"> 
       @Html.RadioButtonFor(model => model.UserType, (int)UserType.Company, new { @id= "Class_UserType" }) Company 
       @{Html.ValidateFor(model => model.UserType);} 
      </div> 
      <div class="editor-field"> 
       @Html.RadioButtonFor(model => model.UserType, (int)UserType.Individual, new { @id = "Class_UserType" }) Individual 
       @{Html.ValidateFor(model => model.UserType);} 
      </div> 
     </div> 
    </div> 
    <div class="Company"> 
      HTML Tags inside 
    </div> 
    <div class="Person"> 
     HTML Tags inside 
    </div> 

此代碼應隱藏各自的div公司/人,正常工作時。我看了很多樣品,但無法弄清楚我在這裏做錯了什麼!任何幫助將不勝感激。

以下是相關的HTML輸出:

<div class="new_row"> 
     <div class="editor-label"> 
      <label for="UserType">*User Type</label> 
     </div> 
     <div class="editor-field"> 
      <div class="editor-field"> 
       <input data-val="true" data-val-number="The field *User Type must be a number." data-val-required="The *User Type field is required." id="Class_UserType" name="UserType" type="radio" value="1" /> Company 
      </div> 
      <div class="editor-field"> 
       <input checked="checked" id="Class_UserType" name="UserType" type="radio" value="2" /> Individual 
      </div> 
     </div> 
    </div> 

回答

2

以下的伎倆對我來說:

$('.UserType').change(function() { 
     var value = $(this).filter(':checked').val(); 
     if (value == "1") { 
      $('.Person').hide(); 
      $('.Company').show(500); 
     } 
     else if (value == "2") { 
      $('.Company').hide(); 
      $('.Person').show(500); 
     } 
    }); 

首先,我需要定義一個通用類按低於我的html:

<div class="editor-field"> 
       @Html.RadioButtonFor(model => model.UserType, (int)UserType.Company, new { @id= "Class_UTCompany", @class="UserType" }) Company 
       @{Html.ValidateFor(model => model.UserType);} 
      </div> 
      <div class="editor-field"> 
       @Html.RadioButtonFor(model => model.UserType, (int)UserType.Individual, new { @id = "Class_UTIndividual", @class="UserType" }) Individual 
       @{Html.ValidateFor(model => model.UserType);} 
    </div> 

其次,我期待在int中的值,這是導致錯誤。我能夠通過放置調試器來發現這一點;在我的JavaScript代碼。

相關問題