2013-12-23 39 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代码。

相关问题