如何在TextBoxFor';的输入在数据库中不存在
本文关键字:输入 数据库 不存在 TextBoxFor | 更新日期: 2023-09-27 18:26:33
NPG_Chemical_Measurement_Methods
是ICollection
类型。在我的Chemical.cshtml
中,我有:
<div id="nioshs">
@Html.EditorFor(model => model.NPG_Chemical_Measurement_Methods)
</div>
在EditorTemplate
视图中:
<div class="method" style="display:inline-block;">
<p>
@Html.RemoveLink("x", "div.method", "input.mark-for-delete")
@Html.HiddenFor(x => x.DeleteMethod, new { @class = "mark-for-delete" })
@Html.TextBoxFor(x => x.Measurement_Method)
@Html.ValidationMessageFor(model => model.Measurement_Method, "", new { @class = "text-danger" })
@Html.Hidden("Measurement_Type", "NIOSH")
</p>
</div>
我想有一些东西,比如当我输入@Html.TextBoxFor(x => x.Measurement_Method)
,然后点击当前页面的其他地方时,如果在Measurement_Method
表中找不到记录,就会弹出一个警告,说Not exist in Database
。
NPG_Chemical.cs具有:
public partial class NPG_Chemical
{
public NPG_Chemical()
{
this.NPG_Chemical_Measurement_Methods = new HashSet<NPG_Chemical_Measurement_Method>();
}
[StringLength(256)]
[Remote("IsUserExists", "NPG_Chemical", ErrorMessage = "Chemical Name already in use")]
public string Chemical { get; set; }
public virtual ICollection<NPG_Chemical_Measurement_Method> NPG_Chemical_Measurement_Methods { get; set; }
internal void CreateMeasurementMethods(int count = 1)
{
for (int i = 0; i < count; i++)
{
NPG_Chemical_Measurement_Methods.Add(new NPG_Chemical_Measurement_Method());
}
}
Measurement_Method.cs具有:
public partial class NPG_Chemical_Measurement_Method
{
[StringLength(256)]
[Remote("IsNIOSHExists", "NPG_Chemical", ErrorMessage = "NIOSH number does not exist")]
public string Measurement_Method { get; set; }
}
NPG_ChemicalController具有:
public JsonResult IsUserExists(string Chemical)
{
return Json(!db.NPG_Chemical.Any(x => x.Chemical == Chemical), JsonRequestBehavior.AllowGet);
}
public JsonResult IsNIOSHExists(string Measurement_Method)
{
System.Diagnostics.Debug.WriteLine("value:",Measurement_Method);
return Json(db.NPG_NIOSH_Method.Any(x => x.Measurement_Number == Measurement_Method), JsonRequestBehavior.AllowGet);
}
希望这能让你接近。我只是凭记忆写的。但基本上,一种方法是用javascript函数处理文本框的onblur事件。然后对发送Measurement_Method值的控制器执行ajax调用,验证数据并返回true或false。如果为false,则显示一个警告框。您需要包含jquery库才能使用它。
@Html.TextBoxFor(x => x.Measurement_Method, new {onblur = "Validate()"})
然后javascript
function Validate() {
$.ajax({
url: "@Url.Action("CheckTextField", "Controller")'?value=" + $('#Measurement_Method').val(),
dataType: "html",
success: function(data) {
if (data == "false")
{
alert('Not exist in Database');
}); }
您的控制器
public string CheckTextField(string value)
{
//validate the value here
return "true" or "false"
}