如何验证级联选择列表?

Zhi Lv - MSFT 32,436 信誉分 Microsoft 供应商
2024-03-26T05:55:22.0933333+00:00

我创建了两个选择列表。更改其中一个的值将显示另一个的值。

函数的功能是正确的,但验证没有起作用。<span asp-validation-for="VenderID" class="text-danger"></span> 的错误消息没有显示。

但是,如果我使用警报,则第一个选择列表的警报有效,即使下一个选择列表为空,程序也会继续运行,而不会显示警报或 <span asp-validation-for="CompanyID" class="text-danger"></span> 的错误消息。

如果有经验的人能够解决这个问题,将会很有帮助。

@model RedwoanEntDistributor.Models.Product.tbl_product 
<div >     
	<select asp-for="VenderID" asp-items="ViewBag.vender" id="VenderDrop">         
		<option value="0">---Select Vender Name----</option>     
	</select> 
</div> 
<div> 	
	<span asp-validation-for="VenderID" class="text-danger"></span> 
</div> 
<div> 	
	<select asp-for="CompanyID" id="CompanyDrop"> 		
		<option value="0">---Select Company Name----</option> 	
	</select> 
</div> 	 	
<div> 	
	<span asp-validation-for="CompanyID" class="text-danger"></span> 	
</div> 	
<div> 	
	<button id="btnadd" onclick="addata()">Save</button> 	
</div>  
<script>  	
	$('#VenderDrop').change(function () 
	{ 
		var id = $(this).val(); 		
		$('#CompanyDrop').empty(); 		
		$('#CompanyDrop').append('<option>---Select Company Name----</option>');  		
		$.ajax({
			url: '/Home/Compnayname?id=' + id, 			
			success: function (result) { 				
				$.each(result, function (i, data) { 					
				$('#CompanyDrop').append('<option value=' + data.company_ID + '>' + data.compnay_Name + '</option>'); 
				}); 			
			} 		
		});  	
	}); 	
	function addata() {  		
		if ($('#VenderDrop').val() == 0) { 		    
			alert("Select Vender Name") 		    
			return false;
		}; 		
		if ($('#CompanyDrop').val() == 0) 
		{
			alert("Select Company Name") 			
			return false;
		};  		
		alert("program is running")}  
</script>
public IActionResult Index(){             
	ViewBag.vender = new SelectList(_context.tbl_Venders.ToList(), "vender_ID", "vender_Name");                         
	return View();         
}
         
public JsonResult Compnayname(int id){
	var compnay = _context.tbl_Compnays.Where(x => x.vender_ID == id).ToList();             
	return Json(compnay);         
}
public int productID { get; set; }   
       
[Required(ErrorMessage = "Select Vender Name")]         
public int VenderID { get; set; }   
      
[Required(ErrorMessage = "Select Company Name")]         
public int CompanyID { get; set; }

注意: 此问题总结整理于:How to Validate Cascading Selectlist

ASP.NET Core
ASP.NET Core
.NET Framework 中一套用于生成 Web 应用程序和 XML Web 服务的技术。
31 个问题
0 个注释 无注释
{count} 票

接受的答案
  1. XuDong Peng-MSFT 10,741 信誉分 Microsoft 供应商
    2024-03-27T01:28:02.1433333+00:00

    你好,

    请检查一下我的测试结果是否满足你的需求:

    Animation6

    代码如下:

    @model WebAppMvc.Models.HelloViewModel;
     
    <form asp-controller="Hello" asp-action="Index" method="post">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="UserName" class="control-label"></label>
            <input asp-for="UserName" class="form-control" />
            <span asp-validation-for="UserName" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="CountryId" class="control-label"></label>
            <select id="selectCountry" class="form-control" asp-for="CountryId"
                    asp-items="@(new SelectList(Model.Countries, nameof(Country.Id), nameof(Country.Name)))">
                <option value="" hidden disabled selected>Select a country</option>
            </select>
            <span asp-validation-for="CountryId" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="CityId" class="control-label"></label>
            <select id="selectCity"  class="form-control" asp-for="CityId"
                    asp-items="@(new SelectList(Model.Cities, nameof(City.Id), nameof(City.Name)))">
                <option value="" hidden disabled selected>Select a city test</option>
            </select>
            <span asp-validation-for="CityId"></span>
        </div>
        <div class="form-group">
            <input type="submit" value="Save" class="btn btn-primary" />
        </div>
    </form>
     
    @section Scripts{
        <script>
            $('#selectCountry').change(function () {
                var id = $(this).val();
                $('#selectCity').empty();
                $('#selectCity').append('<option value="0">---Select a city----</option>');
                $.ajax({
                    url: '/Hello/getCities?id=' + id,
                    success: function (result) {
                        console.info(result);
                        $.each(result, function (i, data) {
                            console.info(i);
                            console.info(data);
                            $('#selectCity').append('<option value=' + data.id + '>' + data.name + '</option>');
                        });
                    }
                });
            });
        </script>
    }
    

    控制器代码如下:

    public class HelloController : Controller
    {
        public IActionResult Index()
        {
            HelloViewModel model = new HelloViewModel
            {
                Countries = new List<Country>
                {
                    new Country { Id = 1, Name = "Country1" },
                    new Country { Id = 2, Name = "Country2" }
                },
                Cities = new List<City> {
                    new City { Id = 11, Name="City1",CountryId = 1},
                    new City { Id = 22, Name="City2",CountryId = 1},
                }
            };
       
            return View(model);
        }
     
    [HttpPost]
        public IActionResult Index(HelloViewModel model) {
            HelloViewModel temp = new HelloViewModel
            {
                Countries = new List<Country>
                {
                    new Country { Id = 1, Name = "Country1" },
                    new Country { Id = 2, Name = "Country2" }
                },
                Cities = new List<City> {
                    new City { Id = 11, Name="City1",CountryId = 1},
                    new City { Id = 22, Name="City2",CountryId = 1},
                }
            };
            return View(temp);
        }
     
    public List<City> getCities(int id) {
            var res = new List<City>();
            if (id == 1)
            {
                return new List<City> {
                    new City { Id = 11, Name="City1",CountryId = 1},
                    new City { Id = 22, Name="City2",CountryId = 1},
                };
            }
            else {
                return new List<City> {
                    new City { Id = 33, Name="City3",CountryId = 2},
                    new City { Id = 44, Name="City4",CountryId = 2},
                };
            }
        }
    }
     
    public class Country
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
     
    public class City
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int CountryId { get; set; }
    }
     
    public class HelloViewModel {
        [Required]
        public string UserName { get; set; }
        //[Required(ErrorMessage = "Select a country11")]
        [Range(1, int.MaxValue, ErrorMessage = "Select a country11")]
        public int CountryId { get; set; }
     
    public List<Country> Countries { get; set; }
        //[Required(ErrorMessage = "Select a city11")]
        [Range(1, int.MaxValue, ErrorMessage = "Select a city11")]
        public int CityId { get; set; }
        public List<City> Cities { get; set; }
    }
    

    在你的代码中,前端和后端都有验证。你在 "addata()" 中使用了 JavaScript 来验证选择项,这也可以,但在这种情况下,[Required(ErrorMessage = "Select Vender Name")] 没有意义。当你像我分享的那样使用表单提交时,模型验证会起作用。


    如果答案是正确的,请点击“接受答案”并点赞。 如果您对此答案还有其他疑问,请点击“评论”。 注意:如果您想接收相关电子邮件,请按照我们的文档中的步骤启用电子邮件通知 此线程的通知。

    0 个注释 无注释

0 个其他答案

排序依据: 非常有帮助

你的答案

问题作者可以将答案标记为“接受的答案”,这有助于用户了解已解决作者问题的答案。