在asp.net mvc 3中单击submitbutton后如何保持选中的值?

时间:2012-07-05 10:43:50

标签: c# asp.net-mvc asp.net-mvc-3

你好;我有2个下拉列表。一个是客户ddl另一个是工作。我想在任何选择过程后保持活着的选定值。但是我不能。 我想在ddl'选择的项目上保持选定的值单击按钮后。 (我使用过2种方法:dropdownlist和dropdownlistfor。)我最喜欢的文章是http://stackoverflow.com/questions/6981698/how-to-keep-dropdownlist-selected-value-after-postback  和 http://stackoverflow.com/questions/4950798/how-to-post-the-selected-value-of-a-selectlist-to-the-controller-using-a-view-mo

视图模型:


 public class MyViewModel
    {
        public IEnumerable<string> Columns { get; set; }
        public IEnumerable<dynamic> Values { get; set; }
        public bool HasNext { get; set; }
        public bool HasPrevious { get; set; }
        public IEnumerable<CustomerModel> Customers { get; set; }
        public IEnumerable<SelectListItem> Jobs { get; set; }
    }
  

Cotroller:


      public class JobController : Controller
      {
        public ActionResult Index(int? page)
        {
            var model = new MyViewModel();
            model.Customers = CustomerOperation.GetCustomers().Items;
            ViewData["Jobs"] = new SelectList(JobOperation.GetCustomersAssemblyList().Items, "scheduleId", "name", null);
            return View(model);
        }

查看:



 <table style="padding:25px; margin:10px 10px 10px 10px; width:800px" id="sample">
                <tr>
                <td>Customer Name: </td>
                <td>
               <%= Html.DropDownListFor(X=>X.Customers,new SelectList(Model.Customers,"Id","Name"),"** Please Select **", new { id = "ddlCustomers" })%>
               </td>
                <td>Job Name:</td>
                <td>
              <%= Html.DropDownList("Jobs", (IEnumerable<SelectListItem>)ViewData["Jobs"], "** Please Select **", new { id = "ddlJobs", disabled = "disabled" })%>
                </td>
                <td>
                 <input value="monitor" name="submitButton" type="submit" />
                </td>
                </tr>
                </table>

1 个答案:

答案 0 :(得分:1)

你的模型应该是这样的

public class MyViewModel
{
    public IEnumerable<string> Columns { get; set; }
    public IEnumerable<dynamic> Values { get; set; }
    public bool HasNext { get; set; }
    public bool HasPrevious { get; set; }
    public IEnumerable<CustomerModel> Customers { get; set; }
    public IEnumerable<SelectListItem> Jobs { get; set; }

    public CustomerModel Customer {get; set;}
}

在您看来,添加下拉列表的代码应该是这样的

<%= Html.DropDownListFor(X=>X.Customer,Model.Customers) %>

希望这有帮助。