本文介绍了返回模型以使用 selectlistitem 默认值查看错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我返回我的模型查看一个或多个错误时,我的下拉列表的默认值有一些问题.我在视图中有一个下拉列表,它是从控制器填充的,而同一个视图中的其他空下拉列表在选择第一个下拉列表时填充了 JSON.

 public ActionResult Countrydata(){CountrydetailsViewModel vm= new CountrydetailsViewModel();vm.countries= dal.countries().Select(x => new SelectListItem { Text = x.Name, Value = x.CountryID.ToString() }).ToList();返回视图(vm);}

这里,dal 是我的数据访问层,允许我填充数据库中的国家/地区列表.用于填充视图中国家列表的代码是这样的

 @Html.DropDownListFor(m => m.selectedcountry, new SelectList(Model.countries, "Value", "Text", Model.selectedcountry), "-Select a Country-", new { @class = "ddlist" })

空下拉列表之一如下

 @Html.DropDownListFor(m => m.selectedtown, new SelectList(Enumerable.Empty(), "Value", "Text", Model.selectedtown), "-选择一个城镇/城市-", new { @class = "ddlist" })

此代码运行良好,我第一次到达该页面,因为我为国家下拉列表设置了默认值,即选择一个国家.我使用以下代码发布我的表单.

 [HttpPost][验证AntiForgeryToken]公共 ActionResult 国家数据(CountrydetailsViewModel returnmodel){如果 (!ModelState.IsValid){returnmodel.countries= dal.countries().Select(x => new SelectListItem { Text = x.Name, Value = x.CountryID.ToString() }).ToList();返回视图(返回模型);}return RedirectToAction("主页");}

如果表单包含错误,我的模型将返回到我的视图,默认选择国家/地区下拉列表的发布值,这不是我的目标,因为在国家/地区下拉列表选择更改中使用 JSON 填充的其他下拉列表是空的.因此,我应该选择同一个国家一次来填充其他下拉列表,这很麻烦.为了合乎逻辑,当发生错误时,我想将我的模型以国家/地区下拉列表的默认值发送回我的视图.我正在使用 MVC4 和 VS 2010

解决方案

您需要在控制器方法中填充两个 SelectList 以便将它们传递给视图.在 GET 方法中,第二个将是一个空的 SelectList(假设它是一个创建"方法),但在 POST 方法中,它将根据已选择的国家/地区进行填充.>

你的模型应该包括

公共类 CountrydetailsViewModel{[必填(错误信息 =..")]公众号?SelectedCountry { 获取;放;}[必填(错误信息 =..")]公众号?SelectedTown { 得到;放;}....公共 IEnumerable国家名单{得到;放;}公共 IEnumerableTownList { 获取;放;}}

还有你的控制器方法

public ActionResult Countrydata(){CountrydetailsViewModel vm = new CountrydetailsViewModel();配置视图模型(虚拟机);返回视图(vm);}[HttpPost]公共 ActionResult 国家数据(CountrydetailsViewModel returnmodel){如果(!ModelState.IsValid){配置视图模型(返回模型);返回视图(返回模型);}....//保存并重定向}私有配置视图模型(CountrydetailsViewModel 模型){var country = dal.countries();model.CountryList= countries.Select(x => new SelectListItem{文字 = x.Name,值 = x.CountryID.ToString()});如果(模型.SelectedCountry.HasValue){//调整查询以适合您的属性名称var towns = db.towns.Where(e => e.CountryId == model.SelectedCountry);model.TownList = towns.Select(x => new SelectListItem{文字 = x.Name,值 = x.TownID.ToString()});}别的{model.TownList = new SelectList(Enumerable.Empty());}}

这还允许您在编辑现有 CountrydetailsViewModel 时生成正确的选项和默认选择.

然后在视图中,使用

@Html.DropDownListFor(m => m.SelectedCountry, Model.CountryList, "-Select a Country-", new { @class = "ddlist" })@Html.ValidationMessageFor(m => m.SelectedCountry)@Html.DropDownListFor(m => m.SelectedTown, Model.TownList, "-选择一个国家-", new { @class = "ddlist" })@Html.ValidationMessageFor(m => m.SelectedTown)

请注意,从您使用 new SelectList(..) 传递给视图的原始文件创建相同的 SelectList 是没有意义的 - 这只是不必要的额外开销.另请注意,当您绑定到模型属性时,将忽略 SelectList 构造函数中的最后一个参数(该方法在内部根据属性值构建自己的 SelectList) -你可以把你想要的任何值作为最后一个参数,你会看到该选项仍然是根据属性值正确选择的.

i have some issues with default value of my dropdownlist when returning my model to view in case of one or many errors. I have a dropdownlist in the view which is filled from the controller and others empty dropdownlists in the same view which are filled with JSON on selection of the first dropdownlist.

    public ActionResult Countriesdata()
    {
    CountrydetailsViewModel vm= new CountrydetailsViewModel();
        vm.countries= dal.countries().Select(x => new SelectListItem { Text = x.Name, Value = x.CountryID.ToString() })
                               .ToList();
   return View(vm);
    }

here, dal is my data access layer and allows me to fill the list of countries from the database. The code use to fill the countries list in the view is like this

  @Html.DropDownListFor(m => m.selectedcountry, new  SelectList(Model.countries, "Value", "Text", Model.selectedcountry), "-Select a Country-", new { @class = "ddlist" })

one of the empty dropdowlists is as the one below

 @Html.DropDownListFor(m => m.selectedtown, new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text", Model.selectedtown), "-Select a Town/City-", new { @class = "ddlist" })

This code work very well i reach the page for the first time because i have set a default value for country dropdownlist which is select a country. i use the following code to post my form.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Countriesdata(CountrydetailsViewModel  returnmodel)
    {
     if (! ModelState.IsValid)
        {
  returnmodel.countries= dal.countries().Select(x => new SelectListItem { Text = x.Name, Value = x.CountryID.ToString() })
                               .ToList();
   return View(returnmodel);
        }
        return RedirectToAction("mainpage");
    }

If the form contains errors, my model is returned back to my view with the posted value of country selected dropdownlist as default, which is not my goal because the others dropdowlists which are filled using JSON on the country dropdownlist selection change are empty.Thus, I ought to select this same country once to fill the others dropdowlists, which is cumbersome. To be logic, i would like to send back my model to my view with default value of the dropdowlist of country when an error occurs. I am using MVC4 and VS 2010

解决方案

You need to populate both SelectList's in the controller methods so they get passed to the view. In the GET method, the 2nd one will be an empty SelectList (assuming its a 'Create' metod), but in the POST method it will be populated based on the country that has been selected.

You model should include

public class CountrydetailsViewModel
{
    [Required(Error Message = "..")]
    public int? SelectedCountry { get; set; }
    [Required(Error Message = "..")]
    public int? SelectedTown { get; set; }
    ....
    public IEnumerable<SelectListItem> CountryList{ get; set; }
    public IEnumerable<SelectListItem> TownList { get; set; }
}

And your controller methods

public ActionResult Countriesdata()
{
    CountrydetailsViewModel vm = new CountrydetailsViewModel();
    ConfigureViewModel(vm);
    return View(vm);
}
[HttpPost]
public ActionResult Countriesdata(CountrydetailsViewModel returnmodel)
{
    if(!ModelState.IsValid)
    {
        ConfigureViewModel(returnmodel);
        return View(returnmodel);
    }
    .... // save and redirect
}
private ConfigureViewModel(CountrydetailsViewModel model)
{
    var countries = dal.countries();
    model.CountryList= countries.Select(x => new SelectListItem
    {
        Text = x.Name,
        Value = x.CountryID.ToString()
    });
    if (model.SelectedCountry.HasValue)
    {
        // adjust query to suit your property names
        var towns = db.towns.Where(e => e.CountryId == model.SelectedCountry);
        model.TownList = towns.Select(x => new SelectListItem
        {
            Text = x.Name,
            Value = x.TownID.ToString()
        });
    }
    else
    {
        model.TownList = new SelectList(Enumerable.Empty<SelectListItem>());
    }
}

This also allows you to generate the correct options and default selections when editing an existing CountrydetailsViewModel.

Then in the view, use

@Html.DropDownListFor(m => m.SelectedCountry, Model.CountryList, "-Select a Country-", new { @class = "ddlist" })
@Html.ValidationMessageFor(m => m.SelectedCountry)

@Html.DropDownListFor(m => m.SelectedTown, Model.TownList, "-Select a Country-", new { @class = "ddlist" })
@Html.ValidationMessageFor(m => m.SelectedTown)

Note that there is no point creating an identical SelectList from the original one you passed to the view by using new SelectList(..) - its just unnecessary extra overhead. Note also that the last parameter in the SelectList constructor is ignored when your binding to a model property (internally the method builds its own SelectList based on the value of the property) - you could put whatever value you wanted as the last parameter and you will see that the option is still correct selected based on the value of the property.

这篇关于返回模型以使用 selectlistitem 默认值查看错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 11:52