简体   繁体   English

如何在MVC中的控制器中获取DropDownList SelectedValue

[英]How to get DropDownList SelectedValue in Controller in MVC

I have dropdownlist, which I have filled from database. 我有下拉列表,我已经从数据库中填写了。 Now I need to get the selected value in Controller do some manipulation. 现在,我需要在Controller中获取选定的值,然后进行一些操作。 But not getting the idea. 但是没有主意。 Code which I have tried. 我尝试过的代码。

Model 模型

public class MobileViewModel 
{          
    public List<tbInsertMobile> MobileList;
    public SelectList Vendor { get; set; }
}

Controller 控制者

 public ActionResult ShowAllMobileDetails()
    {
        MobileViewModel MV = new MobileViewModel();
        MV.MobileList = db.Usp_InsertUpdateDelete(null, "", "", null, "", 4, MergeOption.AppendOnly).ToList();
        MV.Vendor = new SelectList(db.Usp_VendorList(), "VendorId", "VendorName");
        return View(MV);
    }

    [HttpPost]
    public ActionResult ShowAllMobileDetails(MobileViewModel MV)
    {           
        string strDDLValue = ""; // Here i need the dropdownlist value

        return View(MV);
    }

View 视图

   <table>           
        <tr>
            <td>Mobile Manufacured</td>
            <td>@Html.DropDownList("ddlVendor", Model.Vendor, "Select Manufacurer") </td>
        </tr>         
        <tr>
            <td>

            </td>
            <td>
                <input id="Submit1" type="submit" value="search" />
            </td>
        </tr>
    </table>

1st Approach (via Request or FormCollection): 第一种方法(通过Request或FormCollection):

You can read it from Request using Request.Form , your dropdown name is ddlVendor so pass ddlVendor key in the formCollection to get its value that is posted by form: 您可以使用Request.FormRequest读取它,您的下拉名称为ddlVendor因此在formCollection中传递ddlVendor键以获取其值,该值由表单发布:

string strDDLValue = Request.Form["ddlVendor"].ToString();

or Use FormCollection : 或使用FormCollection

[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV,FormCollection form)
{           
  string strDDLValue = form["ddlVendor"].ToString();

  return View(MV);
}

2nd Approach (Via Model): 第二种方法(通过模型):

If you want with Model binding then add a property in Model: 如果要使用模型绑定,请在模型中添加一个属性:

public class MobileViewModel 
{          
    public List<tbInsertMobile> MobileList;
    public SelectList Vendor { get; set; }
    public string SelectedVendor {get;set;}
}

and in View: 并在视图中:

@Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")

and in Action: 并在行动中:

[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV)
{           
   string SelectedValue = MV.SelectedVendor;
   return View(MV);
}

UPDATE: 更新:

If you want to post the text of selected item as well, you have to add a hidden field and on drop down selection change set selected item text in the hidden field: 如果还要发布所选项目的文本,则必须添加一个隐藏字段,然后在下拉选择更改中将所选项目的文本设置为隐藏字段:

public class MobileViewModel 
{          
    public List<tbInsertMobile> MobileList;
    public SelectList Vendor { get; set; }
    public string SelectVendor {get;set;}
    public string SelectedvendorText { get; set; }
}

use jquery to set hidden field: 使用jquery设置隐藏字段:

<script type="text/javascript">
$(function(){
$("#SelectedVendor").on("change", function {
   $("#SelectedvendorText").val($(this).text());
 });
});
</script>

@Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")
@Html.HiddenFor(m=>m.SelectedvendorText)

Model 模型

Very basic model with Gender field. 具有性别字段的非常基本的模型。 GetGenderSelectItems() returns select items needed to populate DropDownList. GetGenderSelectItems()返回填充DropDownList所需的选择项。

public enum Gender 
{
    Male, Female
}

public class MyModel
{
    public Gender Gender { get; set; }

    public static IEnumerable<SelectListItem> GetGenderSelectItems()
    {
        yield return new SelectListItem { Text = "Male", Value = "Male" };
        yield return new SelectListItem { Text = "Female", Value = "Female" };
    }
}

View 视图

Please make sure you wrapped your @Html.DropDownListFor in a form tag. 请确保将@Html.DropDownListFor包装在一个表单标签中。

@model MyModel

@using (Html.BeginForm("MyController", "MyAction", FormMethod.Post)
{
   @Html.DropDownListFor(m => m.Gender, MyModel.GetGenderSelectItems())
   <input type="submit" value="Send" />
}

Controller 控制者

Your .cshtml Razor view name should be the same as controller action name and folder name should match controller name eg Views\\MyController\\MyAction.cshtml . 您的.cshtml Razor视图名称应与控制器操作名称相同,并且文件夹名称应与控制器名称匹配,例如Views\\MyController\\MyAction.cshtml

public class MyController : Controller 
{
    public ActionResult MyAction()
    {
        // shows your form when you load the page
        return View();
    }

    [HttpPost]
    public ActionResult MyAction(MyModel model)
    {
        // the value is received in the controller.
        var selectedGender = model.Gender;
        return View(model);
    }
}

Going further 更进一步

Now let's make it strongly-typed and enum independent: 现在,让我们使其成为强类型并独立于枚举:

var genderSelectItems = Enum.GetValues(typeof(Gender))
    .Cast<string>()
    .Select(genderString => new SelectListItem 
    {
        Text = genderString,
        Value = genderString,
    }).AsEnumerable();

MVC 5/6/Razor Pages MVC 5/6 / Razor页面

I think the best way is with strongly typed model, because Viewbags are being aboused too much already :) 我认为最好的方法是使用强类型模型,因为Viewbags已经被夸大了很多:)

MVC 5 example MVC 5示例

Your Get Action 您采取行动

public async Task<ActionResult> Register()
    {
        var model = new RegistrationViewModel
        {
            Roles = GetRoles()
        };

        return View(model);
    }

Your View Model 您的视图模型

    public class RegistrationViewModel
    {
        public string Name { get; set; }

        public int? RoleId { get; set; }

        public List<SelectListItem> Roles { get; set; }
    }    

Your View 您的看法

    <div class="form-group">
        @Html.LabelFor(model => model.RoleId, htmlAttributes: new { @class = "col-form-label" })
        <div class="col-form-txt">
            @Html.DropDownListFor(model => model.RoleId, Model.Roles, "--Select Role--", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.RoleId, "", new { @class = "text-danger" })
        </div>
    </div>                                   

Your Post Action 您的张贴动作

    [HttpPost, ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegistrationViewModel model)
    {
        if (ModelState.IsValid)
        {
            var _roleId = model.RoleId, 

MVC 6 It'll be a little different MVC 6会有所不同

Get Action 采取行动

public async Task<ActionResult> Register()
    {
        var _roles = new List<SelectListItem>();
        _roles.Add(new SelectListItem
        {
           Text = "Select",
           Value = ""
        });
        foreach (var role in GetRoles())
        {
          _roles.Add(new SelectListItem
          {
            Text = z.Name,
            Value = z.Id
          });
        }

        var model = new RegistrationViewModel
        {
            Roles = _roles
        };

        return View(model);
    }

Your View Model will be same as MVC 5 您的视图模型将与MVC 5相同

Your View will be like 您的观点将像

<select asp-for="RoleId" asp-items="Model.Roles"></select>

Post will also be same 帖子也将相同

Razor Pages 剃刀页面

Your Page Model 您的页面模型

[BindProperty]
public int User User { get; set; } = 1;

public List<SelectListItem> Roles { get; set; }

public void OnGet()
{
    Roles = new List<SelectListItem> {
        new SelectListItem { Value = "1", Text = "X" },
        new SelectListItem { Value = "2", Text = "Y" },
        new SelectListItem { Value = "3", Text = "Z" },
   };
}

<select asp-for="User" asp-items="Model.Roles">
    <option value="">Select Role</option>
</select>

I hope it may help someone :) 我希望它可以帮助某人:)

Use SelectList to bind @HtmlDropdownListFor and specify selectedValue parameter in it. 使用SelectList绑定@HtmlDropdownListFor并在其中指定selectedValue参数。

http://msdn.microsoft.com/en-us/library/dd492553(v=vs.108).aspx http://msdn.microsoft.com/zh-CN/library/dd492553(v=vs.108).aspx

Example : you can do like this for getting venderid 示例:您可以这样做以获得venderid

@Html.DropDownListFor(m => m.VendorId,Model.Vendor)


   public class MobileViewModel 
   {          
    public List<tbInsertMobile> MobileList;
    public SelectList Vendor { get; set; }
    public int VenderID{get;set;}
   }
   [HttpPost]
   public ActionResult Action(MobileViewModel model)
   {
            var Id = model.VenderID;

If you're looking for something lightweight, I'd append a parameter to your action. 如果您正在寻找轻量级的东西,我会在您的操作中附加一个参数。

[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV, string ddlVendor)
{           
    string strDDLValue = ddlVendor; // Of course, this becomes silly.

    return View(MV);
}

What's happening in your code now, is you're passing the first string argument of "ddlVendor" to Html.DropDownList , and that's telling the MVC framework to create a <select> element with a name of "ddlVendor." 现在,您的代码中正在发生的事情是将“ ddlVendor”的第一个字符串参数传递给Html.DropDownList ,这告诉MVC框架创建一个name为“ ddlVendor”的<select>元素。 When the user submits the form client-side, then, it will contain a value to that key. 当用户提交客户端表单时,它将包含该键的值。

When MVC tries to parse that request into MV , it's going to look for MobileList and Vendor and not find either, so it's not going to be populated. 当MVC尝试将该请求解析为MV ,它将查找MobileListVendor而不找到两者,因此不会被填充。 By adding this parameter, or using FormCollection as another answer has suggested, you're asking MVC to specifically look for a form element with that name, so it should then populate the parameter value with the posted value. 通过添加此参数,或使用FormCollection作为另一个建议的答案,您是在要求MVC专门查找具有该名称的表单元素,因此,它随后应使用发布的值填充参数值。

I was having the same issue in asp.NET razor C# 我在ASP.NET剃须刀C#中遇到相同的问题

I had a ComboBox filled with titles from an EventMessage , and I wanted to show the Content of this message with its selected value to show it in a label or TextField or any other Control ... 我有一个ComboBox填充了EventMessage标题,我想显示此消息的内容及其选定的值,以在标签, TextField或任何其他Control显示它。

My ComboBox was filled like this: 我的ComboBox是这样填充的:

 @Html.DropDownList("EventBerichten", new SelectList(ViewBag.EventBerichten, "EventBerichtenID", "Titel"), new { @class = "form-control", onchange = "$(this.form).submit();" })

In my EventController I had a function to go to the page, in which I wanted to show my ComboBox (which is of a different model type, so I had to use a partial view)? 在我的EventController我有一个转到页面的函数,我想在其中显示我的ComboBox (它是不同的模型类型,因此我必须使用局部视图)?

The function to get from index to page in which to load the partial view: 从索引到要加载部分视图的页面的函数:

  public ActionResult EventDetail(int id)
        {

            Event eventOrg = db.Event.Include(s => s.Files).SingleOrDefault(s => s.EventID == id);
            //  EventOrg eventOrg = db.EventOrgs.Find(id);
            if (eventOrg == null)
            {

                return HttpNotFound();
            }
            ViewBag.EventBerichten = GetEventBerichtenLijst(id);
            ViewBag.eventOrg = eventOrg;
            return View(eventOrg);
        }

The function for the partial view is here: 局部视图的功能在这里:

 public PartialViewResult InhoudByIdPartial(int id)
        {
            return PartialView(
                db.EventBericht.Where(r => r.EventID == id).ToList());

        }

The function to fill EventBerichten: 填充EventBerichten的函数:

        public List<EventBerichten> GetEventBerichtenLijst(int id)
        {
            var eventLijst = db.EventBericht.ToList();
            var berLijst = new List<EventBerichten>();
            foreach (var ber in eventLijst)
            {
                if (ber.EventID == id )
                {
                    berLijst.Add(ber);
                }
            }
            return berLijst;
        }

The partialView Model looks like this: 部分视图模型如下所示:

@model  IEnumerable<STUVF_back_end.Models.EventBerichten>

<table>
    <tr>
        <th>
            EventID
        </th>
        <th>
            Titel
        </th>
        <th>
            Inhoud
        </th>
        <th>
            BerichtDatum
        </th>
        <th>
            BerichtTijd
        </th>

    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.EventID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Titel)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Inhoud)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.BerichtDatum)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.BerichtTijd)
            </td>

        </tr>
    }
</table>

VIEUW : This is the script used to get my output in the view VIEUW :这是用于在视图中获取输出的脚本

<script type="text/javascript">
    $(document).ready(function () {
        $("#EventBerichten").change(function () {
            $("#log").ajaxError(function (event, jqxhr, settings, exception) {
                alert(exception);
            });

            var BerichtSelected = $("select option:selected").first().text();
            $.get('@Url.Action("InhoudByIdPartial")',
                { EventBerichtID: BerichtSelected }, function (data) {
                    $("#target").html(data);
                });
        });
    });
            </script>
@{
                    Html.RenderAction("InhoudByIdPartial", Model.EventID);
                } 

<fieldset>
                <legend>Berichten over dit Evenement</legend>
                <div>
                    @Html.DropDownList("EventBerichten", new SelectList(ViewBag.EventBerichten, "EventBerichtenID", "Titel"), new { @class = "form-control", onchange = "$(this.form).submit();" })
                </div>

                <br />
                <div id="target">

                </div>
                <div id="log">

                </div>
            </fieldset>

Thanks - this helped me to understand better ansd solve a problem I had. 谢谢-这有助于我更好地了解和解决我遇到的问题。 The JQuery provided to get the text of selectedItem did NOT wwork for me I changed it to 提供的用于获取selectedItem文本的JQuery对我不起作用,我将其更改为

$(function () {
  $("#SelectedVender").on("change", function () {
   $("#SelectedvendorText").val($(**"#SelectedVender option:selected"**).text());
  });
});

If you want to use @Html.DropDownList , follow. 如果要使用@Html.DropDownList ,请遵循。

Controller: 控制器:

var categoryList = context.Categories.Select(c => c.CategoryName).ToList();

ViewBag.CategoryList = categoryList;

View: 视图:

@Html.DropDownList("Category", new SelectList(ViewBag.CategoryList), "Choose Category", new { @class = "form-control" })

$("#Category").on("change", function () {
 var q = $("#Category").val();

console.log("val = " + q);
});

Simple solution not sure if this has been suggested or not. 简单的解决方案不确定是否建议这样做。 This also may not work for some things. 对于某些事情,这可能也不起作用。 That being said this is the simple solution below. 话虽如此,这是下面的简单解决方案。

new SelectListItem { Value = "1", Text = "Waiting Invoices", Selected = true}

List<SelectListItem> InvoiceStatusDD = new List<SelectListItem>();
InvoiceStatusDD.Add(new SelectListItem { Value = "0", Text = "All Invoices" });
InvoiceStatusDD.Add(new SelectListItem { Value = "1", Text = "Waiting Invoices", Selected = true});
InvoiceStatusDD.Add(new SelectListItem { Value = "7", Text = "Client Approved Invoices" });

@Html.DropDownList("InvoiceStatus", InvoiceStatusDD)

You can also do something like this for a database driven select list. 您还可以对数据库驱动的选择列表执行类似的操作。 you will need to set selected in your controller 您将需要在控制器中设置selected

@Html.DropDownList("ApprovalProfile", (IEnumerable<SelectListItem>)ViewData["ApprovalProfiles"], "All Employees")

Something like this but better solutions exist this is just one method. 这样的东西,但存在更好的解决方案,这只是一种方法。

foreach (CountryModel item in CountryModel.GetCountryList())
    {
        if (item.CountryPhoneCode.Trim() != "974")
        {
            countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode });

        }
        else {


            countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode,Selected=true });

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM