如何使用Razor和Ajax使用下拉列表

时间:2013-01-23 14:16:01

标签: ajax asp.net-mvc-3 razor asp.net-ajax

我有一个正常工作的ajax功能

$.ajax({
              type: "POST",
              url: urlemp,
              success: function (returndata) {
                  if (returndata.ok) {
                    //  var data = eval("" + returndata.data + "");
                      select.empty();
                      $.each(returndata.data, function (rec) {

                          select.append($('<option>' + returndata.data[rec].Name + '</option>'));
                      });
                      select.show('slow');
                      select.change();
                  }
                  else {
                      window.alert(' error : ' + returndata.message);
                  }

              }
          }
          );

并在视图中我使用此选择器代码

<select id="cmbDept" onload="javascript:cascadingdropdown()"> 
        </select>

现在我想将此选择器的代码更改为Razor类型,如@ Html.xxxx 我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

 public class NamesViewModel
  {
    public string SelectedName { get; set; }
    public IEnumerable<SelectListItem> Name { get; set; }
   }

控制器:

  public class HomeController : Controller
  {
     public ActionResult Index()
     {
      var model = new NamesViewModel();
       // TODO: obviously those will come from your database
      model.Names = new[]
      {
        new SelectListItem { Value = "1", Text = "Mary" },
        new SelectListItem { Value = "2", Text = "Joan" },
        new SelectListItem { Value = "3", Text = "Lisa" },
      };

      // Preselect the option with Value = "Mary"
      // Make sure you have such option in the NAmes list
       model.SelectedName = "Mary";
       return View(model);
      }
      }

     View (~/Views/Home/Index.cshtml):

     @model NamesViewModel

    @Html.DropDownListFor(
        x => x.SelectedName,
       Model.Name, 
       "Select Name"
     )