返回模型以使用selectlistitem默认值查看错误

时间:2016-10-27 22:13:07

标签: c# json asp.net-mvc asp.net-mvc-4

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

    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);
    }

这里,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<SelectListItem>(), "Value", "Text", Model.selectedtown), "-Select a Town/City-", new { @class = "ddlist" })

这段代码非常有效,我第一次到达页面,因为我为国家/地区下拉列表设置了一个默认值,即选择一个国家/地区。我使用以下代码发布我的表单。

    [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");
    }

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

1 个答案:

答案 0 :(得分:1)

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

你的模特应该包括

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; }
}

你的控制器方法

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>());
    }
}

这也允许您在编辑现有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, "-Select a Country-", new { @class = "ddlist" })
@Html.ValidationMessageFor(m => m.SelectedTown)

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

相关问题