Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP MVC验证下拉框_C#_Asp.net Mvc_Validation_Model View Controller_Dropdownlistfor - Fatal编程技术网

C# ASP MVC验证下拉框

C# ASP MVC验证下拉框,c#,asp.net-mvc,validation,model-view-controller,dropdownlistfor,C#,Asp.net Mvc,Validation,Model View Controller,Dropdownlistfor,我在MVC中使用模型验证来验证我的表单 我是这样做的: [MetadataType(typeof(CarModel))] public partial class Car {...} public class CarModel { [Required(ErrorMessage = "Select the brand please")] [Display(Name = "Brand* :")] public object brand_id { get; set; }

我在MVC中使用模型验证来验证我的表单

我是这样做的:

[MetadataType(typeof(CarModel))]
public partial class Car {...}


public class CarModel
{
    [Required(ErrorMessage = "Select the brand please")]
    [Display(Name = "Brand* :")]
    public object brand_id { get; set; }

    ...
 }
List<Brand> brands = Brand.GetAllBrands();
ViewBag.brands = brands;
在我看来,下拉框的代码如下:

@Html.DropDownListFor(m => m.brand_id, new SelectList(ViewBag.brands, "id", "name"), new {@class = "selectBoxes" })
Viewbag.brands的填充方式如下:

[MetadataType(typeof(CarModel))]
public partial class Car {...}


public class CarModel
{
    [Required(ErrorMessage = "Select the brand please")]
    [Display(Name = "Brand* :")]
    public object brand_id { get; set; }

    ...
 }
List<Brand> brands = Brand.GetAllBrands();
ViewBag.brands = brands;
有什么问题?下拉框的创建?或者formvalidation是否工作正常? 品牌名称在下拉框中正确加载,并且没有像-Select-这样的0值,第一个品牌显示在下拉框中。。。但当我发送一个空表单时,它会卡在下拉列表上

编辑:也许问题是汽车使用品牌识别码,而品牌使用识别码?如果是,如何在不更改此字段名称的情况下解决此问题

编辑2:品牌只是Linq品牌的一部分,具有以下功能:

public static List<Brand> GetAllBrands()
{
    db = new CarsDataClassesDataContext();
    return db.Brands.OrderBy(b => b.name).ToList<Brand>();
 }

根据POST方法,如果ModelState无效,它将返回到同一视图,在这种情况下,您必须重新初始化ViewBag.brands

if (ModelState.IsValid)
{
     // perform your logic here
}

// if you reached this code, that means the model validation failed
// so you will have to reinitialize the ViewBag

ViewBag.brands = Brand.GetAllBrands();
return View(car);

请发布品牌类别的定义。创建下拉列表时,ViewBag.brands为空。是否确定已执行初始化代码ViewBag.brands=brands?请使用断点来确保。你能发布你的控制器吗?ViewBag.brands已填充,因为下拉框中显示的品牌名称是正确的,但是当我发送表单时,我得到了错误。。。还是我误解了你?当你说发送表格时,你的意思是提交表格吗?在这种情况下,您必须具有最初获取表单的GET方法和用于提交表单的POST方法。你能展示一下你的行动方法吗?我将表格提交给HttpPost: