c# - 如何在 MVC.net 网页中保留由 @Html.ListBoxFor 做出的选择中的所有值?

标签 c# asp.net-mvc listbox http-post multi-select

问题:我根据 HttpGet 中的数据库查询生成了一个 @Html.ListBoxFor。在我的 HttpPost 期间,我想验证是否至少选择了一个元素。如果没有,我只想添加一条验证消息。

当前结果:我收到消息“请至少选择一项”,但现在选择为空(选择元素在那里,但包含 0 个选项)。我知道 Model.Items 在我的 HttpPost 中将为 null。

问题:如何使用我的模型来持久化 Model.Items 以使其不为空?

其他信息:我试图避免使用 FormCollection 集合 和其他 JavaScript。

--代码--

Controller :

public class HomeController : Controller
{
    public ActionResult Index()
    {
        MyViewModel model = new MyViewModel
        {
            Items = Enumerable.Range(1, 5).Select(x => new SelectListItem
            {
                Value = x.ToString(),
                Text = "item " + x
            })
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {

        return View(model);
    }
}

型号:

public class MyViewModel
{
    public MyViewModel()
    {
        Items = new List<SelectListItem>();
    }


    [Required(ErrorMessage = "Please select at least one item")]
    public string[] SelectedItems { get; set; }

    public IEnumerable<SelectListItem> Items { get; set; }
}

查看:

@model ProjectGenerator.Models.MyViewModel

@using (Html.BeginForm())
{
    @Html.ListBoxFor(x => x.SelectedItems, Model.Items)
    @Html.ValidationMessageFor(x => x.SelectedItems)
    <button type="submit">OK</button>
}

最佳答案

    public IEnumerable<SelectListItem> Items 
    {
        get
        {            
            if (HttpContext.Current.Session["MY_ITEMS_TO_LIST_FOR"] == null)
            {
                return null;
            }
            else
            {
                return (IEnumerable<SelectListItem>)HttpContext.Current.Session["MY_ITEMS_TO_LIST_FOR"];
            }
        }

        set
        {
            if (value.Count() > 0) //http post reset value
            {
                HttpContext.Current.Session["MY_ITEMS_TO_LIST_FOR"] = value;
            }
        }
    }

我用这种方式测试过,效果很好。 还有其他方法,但我发现这更容易。 如果调试项目集的 Items 属性, 您会看到,由于某种原因,这些项目已从 http post 的集合中删除,即使您使用 session. 为了防止 session 中的集合接收到空集合,我使用了 If (Items.Count()> 0)。 您可以扩大这个想法并自定义您的 get 和 set。

关于c# - 如何在 MVC.net 网页中保留由 @Html.ListBoxFor 做出的选择中的所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32490186/

相关文章:

wpf - 禁用可编辑组合框中的鼠标滚轮作为 ItemTemplate

c# - asp.net c# 分配字符串的奇怪问题

c# - 如何在IdentityServer4中添加角色到声明?

javascript - 如何通过ajax传递包含数据和文件的对象数组并在mvc Controller 中检索?

asp.net-mvc - datatype.text 验证什么?

asp.net-mvc - 页面 Controller 模式到底是什么?

c# 在列表框中添加或删除数据

c# - 如何在 Redis 缓存中添加/更新/删除值

c# - 是否有可能有 2 个基类已经继承自某个继承或知道第三个公共(public)类的东西?

WINAPI:捕获列表框中的鼠标单击以添加新项目