0

NPG_Chemical_Measurement_Methods is an ICollection type. In my Chemical.cshtml, I have:

<div id="nioshs">
    @Html.EditorFor(model => model.NPG_Chemical_Measurement_Methods)
</div>

and in the EditorTemplate view:

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

I want to have something like when I give input for @Html.TextBoxFor(x => x.Measurement_Method), then click on other place of the current page, an alert will popup says Not exist in Database if record cannot be found in Measurement_Method table.

NPG_Chemical.cs has:

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 has:

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 has:

    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);
    }
Layla Wang
  • 65
  • 7
  • Use a `[Remote]` attribute on your property - [How to: Implement Remote Validation in ASP.NET MVC](https://msdn.microsoft.com/en-us/library/gg508808(VS.98).aspx) - its not a popup, but will display the validation error in the view –  Dec 11 '15 at 22:57
  • @StephenMuecke I tried that, but if it is not using EditorTemplate, everthing works fine, but not with EditorTemplate. – Layla Wang Dec 13 '15 at 23:54
  • You have not shown you script, or the method that your script calls so impossible to know what your doing wrong. And using an `EditorTemplate` has nothing to do with your issue –  Dec 13 '15 at 23:59
  • @StephenMuecke Please see the updated code. The Chemical Name checking has no problem. I use System.Diagnostics.Debug.WriteLine to debug it, seems like the Measurement_Method cannot get value. – Layla Wang Dec 14 '15 at 00:12
  • That's because your generating a collection and your controls are not named `Measurement_Method` - they are prefixed and have indexers (will be `name="NPG_Chemical_Measurement_Methods[#].Measurement_Method"` if I have interpreted you models correctly). I have previously posted an answer relating to this - I'll try and find it shortly –  Dec 14 '15 at 00:26
  • Have a look at [this](http://stackoverflow.com/questions/27513472/remote-validation-for-list-of-models/27517407#27517407) related answer and the workaround. Note the bug report I made still does not appear to have been resolved yet. –  Dec 14 '15 at 00:33
  • @StephenMuecke I change it to function Validate() { var value = $('#NPG_Chemical_Measurement_Methods_0__Measurement_Method').val(); $.ajax({ url: '@Url.Action("CheckTextField", "NPG_Chemical")\?value='+value, dataType: "html", success: function (data) { if (data == "false") { alert('Does not exist in Database'); } } });} So I can redirect after the alert popup if it does not exist in DB. The question is how to change the id from"0" to #, so it will not always check the first one? – Layla Wang Dec 14 '15 at 01:24
  • You have not indicated how your calling that function, or the `CheckTextField()` method (does it have a parameter `string value`?) but it would not work because you return json, not html. –  Dec 14 '15 at 01:29
  • @StephenMuecke I use public string CheckTextField(string value) so it will return true or false – Layla Wang Dec 14 '15 at 01:36
  • Which means that your ajax call needs to be `dataType: "json",` but there are other problems with your code anyway. Am I correct in assuming you don't want to modify the `jquery.validate.js` file as per the link I gave you? If not I can post an answer showing another way to do it. –  Dec 14 '15 at 01:38
  • @StephenMuecke Yes, I didn't change the .js file since I want to use redirect. And I use dataType "html", it has no problem to check the first textbox. – Layla Wang Dec 14 '15 at 01:46
  • What do you mean _I want to use redirect_? Your making an ajax call and ajax calls do not redirect. –  Dec 14 '15 at 01:47
  • @StephenMuecke OK, here's the requirement. I need a function that can add multiple textboxes when click on "+". When user enter a value in one of the textboxes, there should be a check function to check if the value exist in the database. – Layla Wang Dec 14 '15 at 01:58
  • You current implementation using an editor template wont work if your wanting to dynamically add new `NPG_Chemical_Measurement_Method` methods. Refer the answers [here](http://stackoverflow.com/questions/29161481/post-a-form-array-without-successful/29161796#29161796) and [here](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) to show how it can be done –  Dec 14 '15 at 02:01
  • @StephenMuecke I have no problem to dynamically add new NPG_Chemical_Measurement_Method by using a Helper function – Layla Wang Dec 14 '15 at 02:14
  • Not possible, unless your creating only one item and posting it view ajax or in a separate form and redirecting back (and then you would be generating duplicate `id` attributes (invalid html) –  Dec 14 '15 at 02:16
  • Of are you creating a maximum 6 objects and then un-hiding them to add/edit them. In which case I strongly recommend you read the links to understand how to do this correctly. –  Dec 14 '15 at 02:20

1 Answers1

0

This hopefully will get you close. I'm just writing this from memory. But basically one way to do this is handle an onblur event of your textbox with a javascript function. Then do an ajax call to a controller sending the value of Measurement_Method, validate the data and return true or false. If false show an alert box. You'll need to include the jquery library to use this.

@Html.TextBoxFor(x => x.Measurement_Method, new {onblur = "Validate()"})

Then 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');
        }); }

Your controller

public string CheckTextField(string value)
{
   //validate the value here
  return "true" or "false"
}
TK-421
  • 377
  • 2
  • 11