如何在MVC中将下拉列表中的项设置为默认值 [英] How to set an item in dropdown list as default in MVC

查看:78
本文介绍了如何在MVC中将下拉列表中的项设置为默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在下拉列表中将项目设置为MVC中的默认值

以下代码





Controller.cs

How to set an item in dropdown list as default in MVC
in below code


Controller.cs

var usrModel = new UserRegisterModel();
            Country curid = snwe.Countries.Where(a => a.Country1 == "India").FirstOrDefault(); 
            usrModel.Countries = snwe.Countries.AsEnumerable().Select(C => new SelectListItem
            { 
                Text = C.Country1,
                Value = C.CountryID.ToString().Trim(),
               Selected = C.CountryID == curid.CountryID?true:false
                
            });



View.cshtml


View.cshtml

<li>
    <div class="eq-box">
        <label>@(LocalizationProvider.Current.CountryLabel)*
        <span class="validate-msg">@Html.ValidationMessageFor(m => m.CountryId)</span></label>
        <div class="eq-box-field">
        @Html.DropDownListFor(m => m.CountryId, Model.Countries,  new { @class = "dropdown" })
        </div>
    </div>
</li>

推荐答案

您可以创建一个单独的方法来绑定country dropdown-

You can create a separate method to bind country dropdown-
public static SelectList GetCountries(int selected = 0)
       {
           return new SelectList(Repository.Instance.All<country>(), "Id", "Name", selected);
       }</country>







@Html.DropDownListFor(x=>x.CountryId,GetCountries(x.CountryId),"[Select]")





方法返回类型是 SelectList 所以你不必担心选择项目或任何其他东西。



The method return type is SelectList so you don't need to worry about select item or any other thing.


这篇关于如何在MVC中将下拉列表中的项设置为默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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