2011-08-08 126 views

回答

0

假设选定的项目是帖子的一部分,控制器现在知道它是什么。在ViewData字典中只需输入一个条目,指示应该选择哪个项目(获取时为null或者如果没有选择任何项目)。在视图中,检查该值,如果它不为空,请选择适当的选项。

1

MVC不使用ViewState,这意味着您将需要自己管理值持久性。通常这是通过你的模型完成的。所以,因为你有一个视图模型,如:

public class MyViewModel { } 

而且你的控制器:

public class MyController : Controller 
{ 
    public ActionResult Something() 
    { 
     return View(new MyViewModel()); 
    } 

    public ActionResult Something(MyViewModel model) 
    { 
     if (!ModelState.IsValid) 
      return View(model); 

     return RedirectToAction("Index"); 
    } 
} 

现在,当你通过模型回的数据视图(可能不正确 - 验证失败) ,当您使用DropDownListFor方法,只是通过在值:

@Model.DropDownListFor(m => m.Whatever, new SelectList(...)) 

...等

MVC的模型绑定将负责将数据读入模型中,您只需确保将其传递回视图以再次显示相同的值。

2

做这样的事情:

[HttpPost] 
    public ActionResult Create(FormCollection collection) 
    { if (TryUpdateModel(yourmodel)) 
      { //your logic 
       return RedirectToAction("Index"); 
      } 
      int selectedvalue = Convert.ToInt32(collection["selectedValue"]); 
      ViewData["dropdownlist"] = new SelectList(getAllEvents.ToList(), "EventID", "Name", selectedvalue);// your dropdownlist 
      return View(); 
    } 

并在视图:

<%: Html.DropDownListFor(model => model.ProductID, (SelectList)ViewData["dropdownlist"])%> 
2

更容易,您可以在您的ActionResult输入参数的下拉菜单的姓名(或名称)。您的下拉列表应该位于表单标签中。当ActionResult发布时,ASP.Net将遍历querystrings,表单值和cookie。只要您包含您的下拉列表名称,选定的值将被保留。

在这里我有一个3下拉表单发布到ActionResult的形式。下拉列表名称(不区分大小写):ReportName,Year和Month。

//MAKE SURE TO ACCEPT THE VALUES FOR REPORTNAME, YEAR, AND MONTH SO THAT THEY PERSIST IN THE DROPDOWNS EVEN AFTER POST!!!! 
    [AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult ReportSelection(string reportName, string year, string month) 
    { 
     PopulateFilterDrowdowns(); 
     return View("NameOfMyView"); 
    } 
0

使用HttpRequestBase对象。 在视图中,这应该工作:

@Html.DropDownList("mydropdown", ViewBag.Itens as IEnumerable<SelectListItem>, new { value = Request["mydropdown"] }) 
0

如果你正在建设中的下拉控制器的操作方法列表数据源,你可以选择的值发送给它

控制器:

public ActionResult Index(int serviceid=0) 
      { 


      // build the drop down list data source 
       List<Service> services = db.Service.ToList(); 
       services.Insert(0, new Service() { ServiceID = 0, ServiceName = "All" }); 
       // serviceid is the selected value you want to maintain 
       ViewBag.ServicesList = new SelectList(services, "ServiceID", "ServiceName",serviceid); 

       if (serviceid == 0) 
       { 
        //do something 
       } 
       else 
       { 
        // do another thing 

       } 
       return View(); 
      } 

查看:

//ServiceList is coming from ViewBag 
@Html.DropDownList("ServicesList", null, htmlAttributes: new { @class = "form-control" }) 
相关问题