【问题标题】:Part of ViewModel lost on server side validation部分 ViewModel 在服务器端验证中丢失
【发布时间】:2011-03-17 17:58:32
【问题描述】:

我是 ASP.NET MVC 的新手,遇到以下问题。

让我们从一些代码开始:

视图模型:

public class StatesEditViewModel
{
    [Required]
    public virtual int StateId { get; set; }
    [Required]
    public virtual string Name { get; set; }

    public virtual int CountryId { get; set; }
    public List<Country> Countries { get; set; }
}

控制器:

public ActionResult Edit(int id)
{
    using (DataEntities context = new DataEntities())
    {
        UnitOfWork uow = new UnitOfWork(context);

        State s = uow.States.GetById(id);

        StatesEditViewModel vm = new StatesEditViewModel();
        vm.StateId = s.StateId;
        vm.Name = s.Name;
        vm.CountryId = s.CountryId;

        vm.Countries = = uow.Country.GetAll().ToList<Country>();

        return View(vm);
    }
}


[HttpPost]
public ActionResult Edit(int id, StatesEditViewModel vm) 
{
    if (ModelState.IsValid)
    {
        using (DataEntities context = new DataEntities())
        {
            UnitOfWork uow = new UnitOfWork(context);

            State s = uow.States.GetById(id);
            p.Name = vm.Name;
            p.CountryId = vm.CountryId;

            uow.Commit();

            return RedirectToAction("Index");
        }
    }
    else 
    {
        //vm.Countries <-- This is NULL
        return View(vm);
    }
}

问题在于 vm.Countries 为空。是否有任何选项/解决方案可以避免重新填充 ViewModel 的该部分?

以防万一,我在视图中使用 Telerik ComboBox 控件:

@(Html.Telerik().ComboBox()
        .Name("CountryId")
        .BindTo(new SelectList(Model.Countries, "CountryId", "Name"))
        .SelectedIndex(Model.CountryId)
        .Filterable()
)

谢谢!

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 telerik razor viewmodel


    【解决方案1】:

    国家集合不是表单的一部分,因此它们永远不会发布到服务器。仅发送选定的 id。因此,如果模型无效并且您需要渲染视图,只需从数据存储中重新获取此集合即可:

    [HttpPost]
    public ActionResult Edit(int id, StatesEditViewModel vm) 
    {
        using (var context = new DataEntities())
        {
            if (ModelState.IsValid)
            {
                var uow = new UnitOfWork(context);
                State s = uow.States.GetById(id);
                p.Name = vm.Name;
                p.CountryId = vm.CountryId;
                uow.Commit();
                return RedirectToAction("Index");
            }
            // The model is not valid, we need to
            // redisplay the same view so that the
            // user can fix the errors => fetch the countries collection
            vm.Countries = uow.Country.GetAll().ToList<Country>();
            return View(vm);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多