2012-09-22 107 views
1

这是我第一次写这个板子。我是意大利学生,请原谅我英语不好。很多时候,我用ASP.NET Web Forms开发了我的Web应用程序;现在想迁移到ASP.NET MVC框架。所以我想问大约两个问题:ASP.NET MVC 3和AJAX

  1. 场景1:我有一个视图中的两个DropDownList的(元素)的一种形式。 First DropDownList包含一个类别列表:我希望在第一个DropDownList中更改项目时,第二个会自动加载子类别列表。在Web窗体中,我经常使用UpdatePanel来完成这项工作。但是现在在MVC中我无法使用它。我试图使用jQuery AJAX,但代码不起作用。我怎样才能实现这份工作?请举个例子?

  2. 情景2:我有一个一步一步的向导窗体。所以,我需要一步一步地传递(记住)数据。我在哪里可以记住这些数据?在会议?一个建议?

非常感谢, 弗朗切斯科。

+0

你有什么试过?你说你的代码不起作用,然后向我们展示你的代码,看看有什么不工作。 –

回答

3

1)当用户选择第一个下拉菜单时,可以使用jQuery ajax获取第二个下拉菜单的项目。

假设你的Category类看起来像这样

public class Category 
{ 
    public ID { set;get;} 
    public string Name { set;get;} 
} 
视图

和下拉菜单都是这样

@Html.DropDownListFor(x => x.SelectedCategoryID, 
        new SelectList(Model.Categories, "ID", "Name"), "Select") 

@Html.DropDownListFor(x => x.SelectedSubCategoryID, 
        new SelectList(Model.SubCategories, "ID", "Name"), "Select") 

现在有一些JavaScript来听第一个下拉的变化事件,并获得价值,请对接受类别ID的操作方法进行ajax调用,并返回JSON格式的子类别列表。

<script type="text/javascript"> 
    $(function() { 
     $("#SelectedCategoryID").change(function() { 
      var self = $(this); 
      var items=""; 
      $.getJSON("@Url.Action("Index", "GetSubCategories")?id="+self.val(), 
                    function(data){ 
       $.each(data,function(index,item){ 
        items+="<option value='"+item.ID+"'>"+item.Name+"</option>"; 
       }); 
       $("#SelectedSubCategoryID").html(items); 
      }); 
     }); 
    }); 
</script> 

现在你应该有它返回JSON格式

public ActionResult GetSubCategories(int id) 
{ 
    List<Category> subCategoryList=new List<Category>(); 
    //to do : fill the list of (sub) categories to the 
    // above list for the category id passed to this method. 
    return Json(subCategoryList,Json.RequestBehaviour.AllowGet); 
} 

2)会议应该是不错的(子)分类列表GetSubCategories操作方法。

+0

谢谢,**: - )** – fpellegrino