小编Ali*_* Mn的帖子

将多选列表发布到对象列表 asp.net core 2

我有两个类,称为UserRole

class User
{
    ...
    public List<Role> Roles;
}

class Role
{
    ...
    public int ID;
    public string Name;
}
Run Code Online (Sandbox Code Playgroud)

我也有一个动作(提交)

public IActionResult Submit(User user)
{
    ...
} 
Run Code Online (Sandbox Code Playgroud)

在我的 Index.cshtmlselect

<select multiple="multiple" class="multi-select" id="my_multi_select1" asp-for="Roles" asp-items="ViewBag.Roles"></select> 
Run Code Online (Sandbox Code Playgroud)

ViewBag.Roles价值是

ViewBag.Roles= new SelectList(Role.SelectAll(), "Name", "Name");
Run Code Online (Sandbox Code Playgroud)

问题是,当我发表我的表单,数据这样的发送 ...&Roles=role1,role2&...user.Roles成为空,而我希望有两个角色与名字role1,并role2和它们分配到user.Roles(实际上,我希望ASP这是否)

c# model-binding multi-select asp.net-core-2.0

5
推荐指数
1
解决办法
1万
查看次数

Validator.TryValidateProperty 抛出 ArgumentException

我使用列表验证

public class Test
    {

        [ListValidation(ErrorMessage ="wrong")]
        public List<string> Listt { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

列表验证实现

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class ListValidationAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            var list = value as IList;
            if (list != null)
            {
                return list.Count > 0;
            }
            return false;
        }
    }
Run Code Online (Sandbox Code Playgroud)

当我测试它时

Test t = new Test();
            List<string> str = new List<string>();
            str.Add("haha");
            str.Add("hoho");

            t.Listt = str;

            JsonResult json = ModelValidation.ValidateProperty(t, nameof(t.Listt));
Run Code Online (Sandbox Code Playgroud)

它抛出ArgumentException

{System.ArgumentException: The value …
Run Code Online (Sandbox Code Playgroud)

c# validation model-view-controller attributes asp.net-core

3
推荐指数
1
解决办法
2907
查看次数