如何在数据库中不存在TextBoxFor的输入时弹出警报?

时间:2015-12-11 22:50:27

标签: javascript c# asp.net-mvc asp.net-mvc-3

NPG_Chemical_Measurement_MethodsICollection类型。在我的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")
    &nbsp;&nbsp;&nbsp;
</p>
</div>

我想要为@Html.TextBoxFor(x => x.Measurement_Method)提供输入,然后点击当前页面的其他位置,如果在{{1}中找不到记录,则会弹出警告Not exist in Database } table。

NPG_Chemical.cs有:

Measurement_Method

Measurement_Method.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());
        }
    }

NPG_ChemicalController有:

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; }
}

1 个答案:

答案 0 :(得分:0)

希望能让你走近。我只是从记忆中写下这个。但基本上一种方法是使用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"
}