从Html.DropdownListFor获取文本.... MVC3 [英] Get the text from Html.DropdownListFor....MVC3

查看:113
本文介绍了从Html.DropdownListFor获取文本.... MVC3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型:

public class DocumentModel
{
    public int TypeID { get; set; }
    public List<SelectListItem> DocumentTypes { get; set; }
}

我有一个观点:

  @Html.DropDownListFor(x => x.TypeID, Model.DocumentTypes, "- please select -")

我填充我下拉

        var model = new DocumentModel();
        model.DocumentTypes = GetDocumentTypes(); 

private static List<SelectListItem> GetDocumentTypes()
    {

        var items = new List<SelectListItem>
                        {
                            new SelectListItem
                                {Text = @"Text #1", Value = "1"},
                            new SelectListItem
                                {Text = @"Text #2", Value = "2"},
                        };

        return items;

    }

我有一个控制器动作,当窗体回:

I have a controller action when the form is posted back:

 [HttpPost] 
    public void UploadDocument(DocumentModel model)
    {
        if (ModelState.IsValid)
        {
            // I want to get the text from the dropdown
        }
    }

我如何从我的下拉列表的文本?谢谢

How do i get the text from my drop down list? Thanks

推荐答案

您可以不使用默认的模型绑定得到这个容易。你有这样一个小的解决方法。

You may not get this easily with the default model binding. You have to a small workaround like this.

1)一个新的属性添加到您的模型/视图模型来存储选定的文本

1) Add a new property to your model/viewmodel to store the selected text

public class DocumentModel
{
    public int TypeID { get; set; }
    public List<SelectListItem> DocumentTypes { get; set; }
    public string SelctedType { set;get;}
}

2)使用 Html.HiddenFor 辅助方法来创建的形式隐藏变量此属性。

2) Use Html.HiddenFor Helper method to create a hidden variable in the form for this property

@Html.HiddenFor(x => x.SelctedType)

3):使用一些JavaScript来覆盖提交!即;当用户提交表单,获取从下拉列表中选择文本,并设置该值作为隐藏字段的值。

3) Use little javascript to override the submit ! ie; When user submits the form, Get the selected Text from the dropdown and set that value as the value of the Hidden field.

$(function () {
    $("form").submit(function(){
        var selTypeText= $("#TypeID option:selected").text();
        $("#SelctedType").val(selTypeText);           
    });
});

现在在你的 HTTPPost 操作方法,这将是在 SelectedType 属性中。

Now in your HTTPPost action method, This will be available in the SelectedType property.

[HttpPost]
public void UploadDocument(DocumentModel model)
{
   if(ModelState.IsValid)
   {
      string thatValue=model.SelectedType;
   }
}

这篇关于从Html.DropdownListFor获取文本.... MVC3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆