Mvc-项目遇到问题解决办法

时间:2021-10-17 01:31:58

项目中验证

在@using (Html.BeginForm()) 后边都有 @Html.ValidationSummary(),

@Html.ValidationSummary(true, "", new { @class = "text-danger" })

应用其他人

源码:
<div class="validation-summary-valid" data-valmsg-summary="true"><ul><li style="display:none"></li>
</ul></div
<input data-val="true" data-val-number="字段 Id 必须是一个数字。" data-val-required="Id 字段是必需的。" id="Id" name="Id" type="hidden" value="20" />  
<input data-val="true" data-val-number="字段 TypeId 必须是一个数字。" data-val-required="TypeId 字段是必需的。" id="TypeId" name="TypeId" type="hidden" value="2" />

给出解释

解释1,

1.input注明要验证是属于前台的,当某各原因导致前台无法进行验证,比如js没有成功加载的,
当后台if (ModelState.IsValid)失败后,错误信息就会显示到 @Html.ValidationSummary()
2.当前后台验证都通过,但某些逻辑验证没有通过,比如用记名密码错误的,可以手工添加错误信息,
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");这个也会显示到@Html.ValidationSummary()

解释补全

[摘要:@Html.ValidationSummary()用于返回表单正在背景考证的效果。 如, 当背景if(ModelState.IsValid)失利后,毛病疑息便会表现到@Html.ValidationSummary(), 当前背景考证皆经过,但某些逻辑考证出有经过,比如:

@Html.ValidationSummary()用于返回表单在后台验证的结果。

如,

当后台if (ModelState.IsValid)失败后,错误信息就会显示到 @Html.ValidationSummary(),

当前后台验证都通过,但某些逻辑验证没有通过,比如用记名密码错误的,可以手工添加错误信息,
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");这个也会显示到@Html.ValidationSummary()

@Html.ValidationSummary()可携带一个bool型参数,true 或者 false。

如,@Html.ValidationSummary(true),true意味着只显示模型层面的错误消息,比如数据模型验证错误,

若为false, 则意味着显示所有信息,信息显示顺序为,属性错误在前,模型错误在后。

MVC Razor语法的一点研究(关于 @Html.ValidationSummary("",new { @class = "text-danger" }))

怎样从控制器后台添加错误信息到浏览器显示。

ModelState.AddModelError("", "我是错误");

手工添加错误信息(在后台的控制器函数中如此添加),

这个会显示到@Html.ValidationSummary()

ASP.NET MVC之下拉框绑定四种方式

一般在下拉框中绑定数据的话,分为几种情况。

(1)下拉框中的数据是写死的,我们直接给出死代码即可。

(2)下拉框中的数据从数据库中读取出来,从而进行显示。

(3)下拉框中直接用枚举显示。

(4)下拉框中一个选择的值改变另外一个下拉框中的值。

关于下拉框中绑定大概就是以上四种方式,接下来我们一一来破解,我们样式利用Bootstrap来表示,顺便也温习温习Bootstrap。

下拉框硬编码【一】

我们在控制器中给出如下数据并利用ViewBag来进行传递

           ViewBag.hard_value = new List<SelectListItem>() {
new SelectListItem(){Value="0",Text="xpy0928"},
new SelectListItem(){Value="1",Text="cnblogs"}
};

在数据中进行如下绑定

  @Html.DropDownList("hard-code-dropdownlist", new SelectList(ViewBag.hard_value, "Value", "Text"), new { @class = "btn btn-success dropdown-toggle form-control" })

下拉框读取数据库【二】

这个要读取数据库,我们就给出一个类测试就ok,并给出默认选中值,测试类:

        public class BlogCategory
{
public int CategoryId { get; set; }
public string CategoryName { get; set; } }

绑定ViewBag传值:

            //从数据库中读取
var categoryList = new List<BlogCategory>() {
new BlogCategory(){CategoryId=1,CategoryName="C#"},
new BlogCategory(){CategoryId=2,CategoryName="Java"},
new BlogCategory(){CategoryId=3,CategoryName="JavaScript"},
new BlogCategory(){CategoryId=4,CategoryName="C"}
};
var selectItemList = new List<SelectListItem>() {
new SelectListItem(){Value="0",Text="全部",Selected=true}
};
var selectList = new SelectList(categoryList, "CategoryId", "CategoryName");
selectItemList.AddRange(selectList);
ViewBag.database = selectItemList;

视图稍加修改:

@Html.DropDownList("database-dropdownlist", ViewBag.database as IEnumerable<SelectListItem>, new { @class = "btn btn-success dropdown-toggle form-control" })

注意:上述视图中 ViewBag.database 需要进行转换否则出现如下错误:

 CS1973: “System.Web.Mvc.HtmlHelper<dynamic>”没有名为“DropDownList”的适用方法,但似乎有一个具有该名称的扩展方法。扩展方法不能进行动态调度。请考虑强制转换动态参数,或调用该扩展方法

但不使用扩展方法语法。

下拉框绑定枚举【三】(一)

我们同样给出一个测试类:

        public enum Language
{
Chinese,
English,
Japan,
Spanish,
Urdu
}

获取枚举值并绑定:

 ViewBag.from_enum = Enum.GetValues(typeof(Language)).Cast<Language>();

视图给出:

  @Html.DropDownList("database-dropdownlist", new SelectList(ViewBag.from_enum), new { @class = "btn btn-success dropdown-toggle form-control" })

下拉框绑定枚举【三】(二)

利用扩展方法  @Html.EnumDropDownListFor 来实现。接下来依次给出两个类来进行演示:

    public class StudentModel
{
[Display(Name = "语言")]
public ProgrammingLanguages Language { get; set; }
}
    public enum ProgrammingLanguages
{
[Display(Name = "ASP.NET")]
ASPNet,
[Display(Name = "C# .NET")]
CSharp,
[Display(Name = "Java")]
Java,
[Display(Name = "Objective C")]
ObjectiveC,
[Display(Name = "Visual Basic .NET")]
VBNet,
[Display(Name = "Visual DataFlex")]
VisualDataFlex,
[Display(Name = "Visual Fortran")]
VisualFortran,
[Display(Name = "Visual FoxPro")]
VisualFoxPro,
[Display(Name = "Visual J++")]
VisualJPlus
}

在视图中进行绑定:

   <div class="form-group">
@Html.LabelFor(model => model.Language, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EnumDropDownListFor(model => model.Language, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Language, "", new { @class = "text-danger" })
</div>
</div>

下拉框选择则另一个下拉框对应改变 【四】

此例最合适的例子莫过于省市选择的案例。我们一起来看看。

(1)所属省、市一级雇员类。

    public class Province
{
public int provinceId { get; set; }
public string provinceName { get; set; }
public string Abbr { get; set; }
}
    public class City
{
public int CityId { get; set; }
public string CityName { get; set; }
public int provinceId { get; set; }
}
    public class Employees
{ [Key]
public int EmployeeId { get; set; } [Required, Display(Name = "雇员名字")]
public string EmployeeName { get; set; } [Required, Display(Name = "地址")]
public String Address { get; set; } [Required, Display(Name = "所属省")]
public int Province { get; set; } [Required, Display(Name = "所在城市")]
public int City { get; set; } [Display(Name = "地区代码")]
public String ZipCode { get; set; } [Required, Display(Name = "联系号码")]
public String Phone { get; set; }
}

(2)初始化数据

 List<Province> provinceList = new List<Province>() {
new Province(){provinceId=1,provinceName="湖南",Abbr="hunan_province"},
new Province(){provinceId=2,provinceName="广东",Abbr="guangdong_province"},
new Province(){provinceId=3,provinceName="吉林",Abbr="jilin_province"},
new Province(){provinceId=4,provinceName="黑龙江",Abbr="heilongjiang_province"}
};

以及绑定ViewBag到下拉框和控制器上的方法:

        [HttpGet]
public ActionResult Create()
{ ViewBag.ProvinceList = provinceList;
var model = new Employees();
return View(model);
} [HttpPost]
public ActionResult Create(Employees model)
{
if (ModelState.IsValid)
{ }
ViewBag.ProvinceList = provinceList;
return View(model);
} public ActionResult FillCity(int provinceId)
{
var cities = new List<City>() {
new City(){CityId=10,CityName="岳阳市",provinceId=1},
new City(){CityId=10,CityName="深圳市",provinceId=2},
new City(){CityId=10,CityName="吉林市",provinceId=3},
new City(){CityId=10,CityName="哈尔滨市",provinceId=4}
};
cities = cities.Where(s => s.provinceId == provinceId).ToList();
return Json(cities, JsonRequestBehavior.AllowGet);
}

(3)视图展示

    @using (Html.BeginForm())
{
@Html.AntiForgeryToken() <div class="form-horizontal">
<h4>注册雇员</h4>
<div class="form-group">
@Html.LabelFor(m => m.EmployeeName, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.EmployeeName, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.EmployeeName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Address, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Address, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Address, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Province, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.Province,
new SelectList(ViewBag.ProvinceList, "provinceId", "provinceName"),
"选择所在省",
new { @class = "form-control", @onchange = "FillCity()" })
@Html.ValidationMessageFor(m => m.Province, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.City, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.City,
new SelectList(Enumerable.Empty<SelectListItem>(), "CityId", "CityName"),
"选择所在市",
new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.City, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.ZipCode, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.ZipCode, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.ZipCode, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Phone, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Phone, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Phone, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-success" />
<a href="/Home/Employees" class="btn btn-warning">Cancel</a>
</div>
</div>
</div>
}

(4)根据省下拉框选择到市下拉框脚本

       function FillCity() {
var provinceId = $(‘#Province‘).val();
$.ajax({
url: ‘/Home/FillCity‘,
type: "GET",
dataType: "JSON",
data: { provinceId: provinceId },
success: function (cities) {
$("#City").html("");
$.each(cities, function (i, city) {
$("#City").append(
$(‘<option></option>‘).val(city.CityId).html(city.CityName));
});
}
});
}