如何在asp.net mvc应用程序中进行列表框的客户端验证

时间:2019-05-04 02:26:15

标签: c# jquery asp.net-mvc

我想对列表框进行客户端验证。我们不能将所有项目从一个列表框移动到另一个列表框。列表框中至少应有一项。

列表框不应完全空白,因为其中至少应包含一项。

您能指导我怎么做吗?感谢您的帮助。

班级

 public class NumberClass
{
    public string currentLeftNumbers { get; set; }
    public IEnumerable<SelectListItem> leftnumbers { get; set; }
    public IEnumerable<int> leftSelectednumbers { get; set; }

    public string currentRightNumbers { get; set; }
    public IEnumerable<SelectListItem> rightnumbers { get; set; }
    public IEnumerable<int> rightSelectednumbers { get; set; }
}

控制器

[HttpGet]
 public ActionResult Index()
{
List<int> items = new List<int>();

for (int i = 1; i <= 20; i++)
{
    items.Add(i);
}

NumberClass num = GetModel(items, new List<int>());

return View(num);
}

[HttpPost]
public ActionResult Index(NumberClass model)
 {
    List<int> left = GetNumbers(model.currentLeftNumbers);
    List<int> right = GetNumbers(model.currentRightNumbers);

  if (model.leftSelectednumbers != null)
  {
    foreach (var i in model.leftSelectednumbers)
    {
        left.Remove(i);
        right.Add(i);
    }
  }

  if (model.rightSelectednumbers != null)
  {
    foreach (var i in model.rightSelectednumbers)
    {
        right.Remove(i);
        left.Add(i);
    }
  }

  return View(GetModel(left, right));
}

  private List<int> GetNumbers(string numbers)
  {
  if (string.IsNullOrWhiteSpace(numbers))
   {
      return new List<int>();
   }
   else
    {
       return numbers.Split(new char[] { ',' }, 
 StringSplitOptions.RemoveEmptyEntries).Select(n => int.Parse(n)).ToList();
    }
   }

  private NumberClass GetModel(IEnumerable<int> left, IEnumerable<int> right)
  {
NumberClass model = new NumberClass();

if (left.Any())
{
    model.currentLeftNumbers = left.Select(n => n.ToString()).Aggregate((x, y) => x + "," + y);
    model.leftnumbers = left.OrderBy(x => x).Select(n => new SelectListItem { Value = n.ToString(), Text = n.ToString() });
}
else
{
    model.leftnumbers = new List<SelectListItem>();
}

if (right.Any())
{
    model.currentRightNumbers = right.Select(n => n.ToString()).Aggregate((x, y) => x + "," + y);
    model.rightnumbers = right.OrderBy(x => x).Select(n => new SelectListItem { Value = n.ToString(), Text = n.ToString() });
}
else
{
    model.rightnumbers= new List<SelectListItem>();
}

return model;

}

Index.cshtml

@using (Html.BeginForm())
{
    <input type="hidden" name="CurrentLeftNumbers" value="@Model.currentLeftNumbers"/>

    <div class="col-md-6" style="font-family:Arial">
        @Html.ListBoxFor(m => m.leftSelectednumbers, Model.leftnumbers, new { size = 20, @class = "listBox" })
        <br />
        <input type="submit" value="move right" />
    </div>

    <input type="hidden" name="CurrentRightNumbers" value="@Model.currentRightNumbers" />

    <div class="col-md-6" style="font-family:Arial">

        @Html.ListBoxFor(m => m.rightSelectednumbers, Model.rightnumbers, new { size = 20, @class = "listBox" })
        <br />
        <input type="submit" value="move left" />
    </div>
}

2 个答案:

答案 0 :(得分:1)

您可以编写脚本进行验证。 检查选择的长度是否==选择的长度可以防止删除。

$('#moveLeft').click(function () {
        var leftselected = $('#leftSelectednumbers').val();

        var length = $('#leftSelectednumbers option').length;
        //alert(length)
        var selected = $('#leftSelectednumbers :selected').length;
        if (length === selected) {
            alert('Can not move all item to right...');
        } else {
            $.each(leftselected, function (key, value) {
                $('#rightSelectednumbers').append($("<option></option>").attr("value", value).text(value));
            });

            $('#leftSelectednumbers :selected').remove();

        }

    })

cshtml文件

@model TestMVC.Controllers.NumberClass
@using (Html.BeginForm())
{
    <div class="col-md-6" style="font-family:Arial">
        @Html.ListBoxFor(m => m.leftSelectednumbers, Model.leftnumbers, new { size = 20, @class = "listBox" })
        <br />
        <input type="button" id="moveLeft" value="move left" />
    </div>

    <div class="col-md-6" style="font-family:Arial">

        @Html.ListBoxFor(m => m.rightSelectednumbers, new List<SelectListItem>(), new { size = 20, @class = "listBox" })
        <br />
        <input type="button" value="move right" />
    </div>

}

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $('#moveLeft').click(function () {
        var leftselected = $('#leftSelectednumbers').val();

        var length = $('#leftSelectednumbers option').length;
        //alert(length)
        var selected = $('#leftSelectednumbers :selected').length;
        if (length === selected) {
            alert('Can not move all item to right...');
        } else {
            $.each(leftselected, function (key, value) {
                $('#rightSelectednumbers').append($("<option></option>").attr("value", value).text(value));
            });

            $('#leftSelectednumbers :selected').remove();

        }

    })

</script>

在移动后更新脚本以进行排序

@model TestMVC.Controllers.NumberClass
@using (Html.BeginForm())
{
    <div class="col-md-6" style="font-family:Arial">
        @Html.ListBoxFor(m => m.leftSelectednumbers, Model.leftnumbers, new { size = 20, @class = "listBox" })
        <br />
        <input type="button" id="moveLeft" value="move left" />
    </div>

    <div class="col-md-6" style="font-family:Arial">

        @Html.ListBoxFor(m => m.rightSelectednumbers, new List<SelectListItem>(), new { size = 20, @class = "listBox" })
        <br />
        <input type="button" value="move right" />
    </div>

}

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $('#moveLeft').click(function () {
        var leftselected = $('#leftSelectednumbers').val();

        var length = $('#leftSelectednumbers option').length;
        //alert(length)
        var selected = $('#leftSelectednumbers :selected').length;
        if (length === selected) {
            alert('Can not move all item to right...');
        } else {
            var currentrightvalue = [];
            $('#rightSelectednumbers option').each(function (item, option) {
                debugger
                currentrightvalue.push(option.value);
            });

            leftselected = leftselected.concat(currentrightvalue);
            leftselected.sort(function(a,b) { return a - b; });
            $('#rightSelectednumbers option').remove();
            $.each(leftselected, function (key, value) {
                $('#rightSelectednumbers').append($("<option></option>").attr("value", value).text(value));
            });

            $('#leftSelectednumbers :selected').remove();


        }

    })

</script>

答案 1 :(得分:0)

只需在您的组合框中添加ID,然后添加JavaScript进行验证

@using (Html.BeginForm())
{
    <input type="hidden" name="CurrentLeftNumbers" value="@Model.currentLeftNumbers"/>

    <div class="col-md-6" style="font-family:Arial">
        @Html.ListBoxFor(m => m.leftSelectednumbers, Model.leftnumbers, new { size = 20, @class = "listBox",   id="cmb_right"})
        <br />
        <input type="submit" value="move right" />
    </div>

    <input type="hidden" name="CurrentRightNumbers" value="@Model.currentRightNumbers" />

    <div class="col-md-6" style="font-family:Arial">

        @Html.ListBoxFor(m => m.rightSelectednumbers, Model.rightnumbers, new { size = 20, @class = "listBox", id="cmb_left" })
        <br />
        <input type="submit" value="move left"  />
    </div>
}

window.onload = function() {
    var form = document.querySelector("form");
    form.onsubmit = submitted.bind(form);
}

function submitted(event) {
   if( document.getElementById("cmb_left").options.length == 0){
    alert("Please move element");
    event.preventDefault();
   }
   if( document.getElementById("cmb_right").options.length == 0){
    alert("Please add element");
    event.preventDefault();
   }
}

您可以在此链接中进一步检查-How can I listen to the form submit event in javascript?