3

Hi I have a form in which the Username field needs to be checked for availability using AJAX. Here is my code..

 <% using (Html.BeginForm()) { %>
        <%: Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.") %>
        <div>
            <fieldset>
                <legend>Account Information</legend>

                <div class="editor-label">
                    <%: Html.LabelFor(m => m.UserName) %>
                </div>
                <% using (Ajax.BeginForm("Checkavailability", new AjaxOptions { UpdateTargetId = "textEntered" }))
                   { %>
 <div class="editor-field">
                    <%: Html.TextBoxFor(m => m.UserName) %>
                    <%: Html.ValidationMessageFor(m => m.UserName) %>
                </div>
  <input type="submit" value="Check Avail" id="Submitt"/><br />
  <span id="textEntered">Nothing Entered</span>
<% } %>


                <div class="editor-label">
                    <%: Html.LabelFor(m => m.Email) %>
                </div>
                <div class="editor-field">
                    <%: Html.TextBoxFor(m => m.Email) %>
                    <%: Html.ValidationMessageFor(m => m.Email) %>
                </div>

                <div class="editor-label">
                    <%: Html.LabelFor(m => m.Password) %>
                </div>
                <div class="editor-field">
                    <%: Html.PasswordFor(m => m.Password) %>
                    <%: Html.ValidationMessageFor(m => m.Password) %>
                </div>

                <div class="editor-label">
                    <%: Html.LabelFor(m => m.ConfirmPassword) %>
                </div>
                <div class="editor-field">
                    <%: Html.PasswordFor(m => m.ConfirmPassword )%>
                    <%: Html.ValidationMessageFor(m => m.ConfirmPassword) %>
                </div>

                <p>
                    <input type="submit" value="Register" />
                </p>
            </fieldset>
        </div>
    <% } %>

The problem is when I click on check avil button the validation appears.. Is there a way to submit just the ajax form and update without submitting the main form?? or any way to implement my check availability logic?

3 Answers 3

4

I removed the AJAX.BeginForm an added Ajax.ActionLink which dosent submit the form .. instead it passes a single paramater to the controller which I need to check.. Here is the code..

 <% using (Html.BeginForm()) { %>
        <%: Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.") %>

            <fieldset>
                   <div class="editor-label">
                    <%: Html.LabelFor(m => m.UserName) %>
                </div>
 <div class="editor-field">
                    <%: Html.TextBoxFor(m => m.UserName) %>
                    <%: Html.ValidationMessageFor(m => m.UserName) %>
                </div>
      <%= Ajax.ActionLink("Checkavailability", "Checkavailability", new { UserName = "" }, new AjaxOptions { UpdateTargetId = "textEntered" }, new { id = "u" })%>



  <span id="textEntered">Nothing Entered</span>



                <p>
                    <input type="submit" value="Register" />
                </p>


            </fieldset>

    <% } %>

Below is the jQuery which is used to set the parameters being passed

  <script type="text/javascript">

       $(document).ready(function () {
           $('#UserName').blur(function () {
               changeActionURL();
           });

       });



       function changeActionURL() {

           if ($("#UserName").val() == "") {
               alert('Please enter your email to check availablity');
           }
           else {


               var url = '<%= new UrlHelper(ViewContext.RequestContext).Action("Checkavailability", "Account") %>' + '?UserName=' + $("#UserName").val();

               $("#u").attr('href', url);
           }
       }




</script>

the controller is..

public string Checkavailability(string UserName)
        {
            if (UserName != "Enter text" && !String.IsNullOrEmpty(UserName))
            {
                string userName = UserName.ToLower();
                NorthwindEntities dbContext = new NorthwindEntities();
                var query = from p in dbContext.Employees
                            where p.FirstName.ToLower() == userName
                            select p;
                IEnumerable<Employee> rec = query.ToList();

                if (rec.Count() == 0)
                {
                    return "You entered: \"" + UserName.ToString() + "\" available ";
                }
                else
                {
                    return "You entered: \"" + UserName.ToString() + "\" already exists " +
                      DateTime.Now.ToLongTimeString();
                }

            }

            return String.Empty;
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Almost there. First of all, you are missing here opening tag for </fieldset>. Furthermore, this should work, but won't enforce the user to input the data required. You want to intercept the submit() action rather or additionally to the blur().
0

If you can afford to move to mvc3 they've built in remote validation attribute just for the task you are solving. So you can have different fields in form checked via ajax call and all in one form.

Comments

0

There is no behavior defined for nested forms in the HTML spec and generally is advised not to do so.

What you can use is Javascript and dynamically changing form's action attribute. Or you can have multiple named submit buttons and in the action check for the used button and perform your computations based on that.

Rather than writing what has been already written, i will give you the link here. Another and very similar way is to give each submit button a different name attribute and only the used one will be sent to the action. That would look like this:

 [AcceptVerbs(HttpVerbs.Post)]
 public ActionResult Create(FormCollection collection)
 {
     try
     {
         string create = Request.Form["create"];
         string cancel = Request.Form["cancel"];

         return RedirectToAction("Index");
     }
     catch
     {
         return View();
     }
 }

4 Comments

Could you please post a code snippet how to check the used button action in controller?
Seems to be a nice, but it dosent solve the problem of validation and dosent support ajax call
How come it doesn't support ajax call? What does that even have to do with that? Just move from Ajax.Beginform to jQuery and something like $get() or $ajax. That is the proper way to use ajax anyways. And in the response you can easily write out the error message.
Thanks for your answer.. I just found a workaround.. I am posting my working code below..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.