我需要在插入数据库之前验证一个输入是否唯一。我在我的模型类中使用了远程验证属性。
DirectoryIndex ""
查看
[Required(ErrorMessage = "Package name Required")]
[Remote("IsNameAvailble", "Package", ErrorMessage = "Sorry!!! This name have entered for another package")]
public string packagename { get; set; }
这是控制器代码
<div class="form-group">
<label class="control-label">Package Name</label>
@Html.TextBoxFor(model => model.package_name, new { @class = "form-control", placeholder = "Name for the Package", type = "text", autofocus = "autofocus", id = "packagename" })
@Html.ValidationMessageFor(model => model.package_name)
</div>
这在添加新名称方面非常有效 但是在编辑部分时如果我们更改其他值(包名称除外,它会检查并显示错误信息)
所以我需要一种方法来检查它与选定的ID(如果我们检查选定的ID,创建功能赢了工作)
请有人建议回答
先谢谢
答案 0 :(得分:1)
步骤1: - 在远程属性中添加 AdditionalFields 。
[Remote("IsNameAvailble", "Package", AdditionalFields = "id", ErrorMessage = "Sorry!!! This name have entered for another package")]
public string packagename { get; set; }
第2步: - 在 IsNameAvailble 方法中传递 id 参数,并添加条件,通过该条件,我们可以检查id是否大于零,然后lamda表达式应该检查具有id和name的记录,否则只需检查名称。
public ActionResult IsNameAvailble(string package_name,int id=0)
{
Dbfile db = new Dbfile ();
var exist= db.GetAllList().FirstOrDefault(m => m.package_name == package_name);
if (exist!= null)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
答案 1 :(得分:0)
要完成此操作,您需要通过以下方式更改Remote Attribute
:
[Remote("IsNameAvailble", "Package", HttpMethod = "POST", AdditionalFields = nameof(PackageId), ErrorMessage = "Sorry!!! This name have entered for another package.")]
您还需要使用以下方法更改方法签名:
public ActionResult IsNameAvailble(YourModel modelData)
{
// You can access PackageName and PackageId by modelData.PackageName and
// model.PackageId
// Also you can check if Id already exist
}
这样您就可以解决编辑视图问题!