1

我的代码中有一个从后端存储库填充的下拉列表。使用HTML5和存储库模式的级联下拉列表

<h3>Upload Course Section Content</h3> 
    <div class="row"> 
    <div class="nine columns"> 
     <label for="name">Select Course:</label> 
     <select id="coursedd" name="courseid" style="height:40px; font-size:18px;"> 
     <option value="0" id ="defaultcid" class ="choosefilter" >----Please Select Course----</option> 
     @foreach (var course in Model.GetCourseList()) 
     { 
     <option value="@course.CourseID" id ="courseid" class ="choosefilter" >@course.Name </option> 
     } 
     </select> 
    </div> 
    </div> 
    <div class="row" style="margin-top:30px;"> 
    <div class="nine columns"> 
     <label for="name" id="namelabel">Select Course Section:</label> 
     <select id="coursesectiondd" name="coursesectionid" style="height:40px; font-size:18px;"> 
     <option value="0" id ="defaultcs" class ="choosefilter" >----Please Select Course Section----</option> 
     @foreach (var courseSection in Model.GetCourseSectionsByCourseID(Model.CourseID)) 
     { 
     <option value="@courseSection.CourseSectionID" id ="coursesectionid" class ="choosefilter" >@courseSection.Title </option> 
     } 
     </select> 
    </div> 
    </div> 

第二个下拉菜单最初是隐藏的,当选择第一个下拉菜单时,我希望填充下拉菜单。我曾尝试使用下面的jQuery和JavaScript,但一直无法这样做。任何人都可以请帮助我得到这个工作:

function GetCourseID() { 

    var id = document.getElementById("coursedd").value; 

    var postData = { 
     'CourseID': id 
    }; 

    $.post('/Admin/GetCourseID/', postData, function (data) { 
     document.getElementById("coursedd").selectedIndex = id; 
     document.getElementByID("coursesectiondd").show(); 
    }); 
}; 

$(function() { 
    $("#coursedd").change(function() { 
     $('#namelabel').show(); 
     $('#title').show(); 
     $('#CourseSectionSubmit').show(); 
     var chosen = document.getElementById("coursedd").value; 
     if (chosen == "0") { 
      $('#namelabel').hide(); 
      $('#coursesectiondd').hide(); 
      $('#file').hide(); 
      $('#filelabel').hide(); 
     } 
     else { 
      $('#coursesectiondd').show() 
      GetCourseID() 
      $('#coursesectiondd').a 
     } 
    }); 
}); 

在我的控制器我有以下,我认为这将更新适当的值的视图模型来然后填充二级下拉列表,但正在显示什么。

[HttpPost] 
    public ActionResult GetCourseID(int courseID) 
    { 
     avm.CourseID = courseID; 
     return View(avm); 
    } 

回答

1

对于初学者来说,$('#coursesectiondd').a似乎是一个非常折线javascript代码。同样,从您的控制器操作中,您将返回一些视图,但在您的AJAX成功回调中,您没有对结果进行任何操作,如更新DOM中的第二个下拉列表。在控制器动作中将结果作为JSON返回,然后在成功回调中使用此JSON绑定第二个下拉列表会更有效。

我写一个关于你如何能做到这一点这里示例:https://stackoverflow.com/a/4459084/29407

+0

嗨达林,是有是在JavaScript中的错误,我已删除。如果我在控制器中更改我的[HttpPost]动作以返回一个整数,那么public int GetCourseID(int courseID){int id = courseID; return id;}我怎么才能使用这个值刷新并填充第二个下拉菜单 – Jay

+0

为什么你要改变这个动作返回一个整数?在ASP.NET MVC控制器中,动作必须返回ActionResults。在我的回答中,我建议你返回JSON(即JsonResult)。请参阅示例我已链接到n我的答案详细说明:http://stackoverflow.com/a/4459084/29407 –

+0

我不确定如何json的工作,一旦我有一个courseID整数,我可以成功地调用我的子部分if能够刷新页面,我认为这可能是一个更简单的解决方案,因为我有一个方法来检索课程部分基于课程的courseID下拉列表 – Jay