1

我有一个下拉列表,我需要在视图中设置选定的值,稍后当用户在下拉列表中选择任何项目时,我需要将其传递给模型。我在控制器中绑定下拉列表像这样..

       [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Index()
        {
            var itemsforDropdown = new List<SelectListItem> {             
               new SelectListItem{ Text = "Amount" , Value = "Amount"},
               new   SelectListItem{Text= "Pound", Value ="Pound"},
                new  SelectListItem {Text ="Percent", Value ="Percent"}            
            };
            ViewBag.ItemsforDrop = itemsforDropdown;
            //ViewData["listitem"] = itemsforDropdown;
            return View("DdlCrossFields");
        }

我的模型中有这样的属性...

public class CrossFieldValidation
{
    [ValueMustbeInRange]
    public string DDlList1
    { get; set; }

    public string SelectedValue
    { get; set; }

    // [Required(ErrorMessage = "Quantity is required")]

    [Display(Name = "Quantity:")]
    public string TxtCrossField
    { get; set; }
}

这是我的观点...

  @using (Html.BeginForm("PostValues", "CrossFieldsTxtboxes"))
  {   
    @Html.ValidationSummary(true)
    <div class ="editor-field">
      @Html.TextBoxFor(m => m.TxtCrossField)
       @Html.ValidationMessageFor(m=>m.TxtCrossField)
    </div>
      @Html.DropDownList("ItemsforDrop", ViewBag.ItemsforDrop as SelectList,"Select A state", new {id= "State"})  
    //here i need to get  the selected value and i need to pass the this on to model fro future purpose " 
    <input id="PostValues" type="Submit" value="PostValues" />
   }

任何人都可以帮助解决这个问题......非常感谢......

4

2 回答 2

0

在您的控制器 [HttpPost] 操作中添加以下内容。

string selectedVal = Request.Form["ItemsforDrop"].ToString();
于 2013-07-30T04:23:46.040 回答
0

我发现很难弄清楚你在这里想要实现什么,但我会设置如下所示的页面。

这样,将使用列表中的选定值CrossFieldValidation发送到PostValues

模型

public class CrossFieldValidation
{
    [ValueMustbeInRange]
    public string DDlList1
    { get; set; }

    /* add the items list into the model */
    public IEnumerable<SelectListItem> Items 
    { get; set; }    

    public string SelectedValue
    { get; set; }

    [Display(Name = "Quantity:")]
    public string TxtCrossField
    { get; set; }
}

控制器

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
    var model = new CrossFieldValidation {
        Items = new [] {             
           new SelectListItem{ Text = "Amount" , Value = "Amount"},
           new SelectListItem{Text= "Pound", Value ="Pound"},
           new SelectListItem {Text ="Percent", Value ="Percent"}            
        }
    };     

    return View(model);
}

看法

 @model CrossFieldValidation
 @using (Html.BeginForm("PostValues", "CrossFieldsTxtboxes"))
  {   
    @Html.ValidationSummary(true)
    <div class ="editor-field">
      @Html.TextBoxFor(m => m.TxtCrossField)
       @Html.ValidationMessageFor(m=>m.TxtCrossField)
    </div>
    @Html.DropDownListFor(m=>m.SelectedValue, new SelectList(Model.Items, "Value", "Text"))  

    <input id="PostValues" type="Submit" value="PostValues" />
   }
于 2013-07-30T04:30:30.753 回答