【发布时间】:2015-02-07 00:59:27
【问题描述】:
我有这个代码来检查城市的重复条目。
public ActionResult Create(City city)
{
var CityCheck= context.Cities.Where(u => u.CityName == city.CityName && u.ContId = city.ContId).FirstOrDefault();
if (CityCheck == null)
{
context.Cities.Add(city);
}
else
{
ModelState.AddModelError("CityName", "City name already exists.");
}
if (ModelState.IsValid)
{
context.Cities.Add(city);
// rest of Code
context.SaveChanges(city);
return RedirectToAction("Index");
}
ViewBag.PossibleCountries = context.Countries.Where(f => f.IsActive == true && f.IsDeleted == false).ToList();
return View(city);
}
效果很好,这是我的 Edit ActioneResult 方法。
[HttpPost]
public ActionResult Edit(City city)
{
var CityCheck = context.Cities.Where(u => u.CityName == city.CityName && u.ContId == city.ContId).FirstOrDefault();
if (CityCheck == null)
{
context.Entry(city).State = EntityState.Modified;
}
else
{
ModelState.AddModelError("CityName", "City name already exists.");
}
if (ModelState.IsValid)
{
//Rest Of Code
context.Entry(city).State = EntityState.Modified;
return RedirectToAction("Index");
}
ViewBag.PossibleCountries = context.Countries.Where(f => f.IsActive == true && f.IsDeleted == false).ToList();
return View(city);
}
它也可以正常工作,在编辑时单击保存按钮而不进行任何更改。它验证我保存为“城市名称已经存在”我想要做的就是:当用户想要编辑和保存具有现有名称的城市时,它不应该让用户继续。但是应该让用户在单击“保存”而不进行任何更改时继续。 我正在使用 ASP.NET MVC 4 和 EF 4。 提前致谢
【问题讨论】:
-
从数据库中获取
City,然后如果发布的值与现有值相同,则跳过验证。如果您想要客户端验证,请使用[Remote]属性。 How to: Implement Remote Validation in ASP.NET MVC
标签: .net asp.net-mvc c#-4.0 entity-framework-4