1
votes

I am having a problem of a partial page update on Asp.net mvc 3 razor that I cannot get through

I have this _LogOn partial view which has 2 text boxes Email and Password and a button connexion for login purpose:

@using (Html.BeginForm())
{

    @Html.ValidationSummary(true)

    <div class="editor-label">
        @Html.LabelFor(model => model.Email)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Email)
        @Html.ValidationMessageFor(model => model.Email)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Password)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Password)
        @Html.ValidationMessageFor(model => model.Password)
    </div>

    <p>
        <input id="submitConnexion" type="submit" value="Connexion" />
        <a id="lnForgetPwd"> Mot de passe oubliƩ</a>
    </p>
}

And here is the controllers: the GET controller does not nothing more than grabbing the _Logon partialV view and hand it to jquery to update a div called Div-2.

    // GET: Account/Logon 
    public ActionResult LogOn()
    {
        return PartialView("_LogOn");
    }

The POST controller is supposed to check that the password is correct, if so it return to Json value of true if login/password is ok, otherwhise refresh the Div-2 with errors.

    // POST: Account/Logon
    [HttpPost]
    public ActionResult LogOn(UserLogon model)
    {
        bool result = false;

        if (ModelState.IsValid)
        {
            UserManager userManager = new UserManager();
            string password = userManager.GetUserPassword(model.Email);

            if (string.IsNullOrEmpty(password))
            {

                ModelState.AddModelError("", "Mot de passe ou email incorrect.");
                result = false;
            }

            if (model.Password == password)
            {
                FormsAuthentication.SetAuthCookie(model.Email, false);
                result = true;
            }
        }

        //return Json(new { JsResult = result });

        return PartialView("_Logon", model);

    }

And here is finally the Ajax Jquery code

    // Ajax call POST for login form button submitConnexion
    $("#submitConnexion").live('click', function () {

        var email = $("#div-2 #Email").val();
        var password = $("#div-2 #Password").val();

        var data = { Email: "hello", Password: password };

        alert(email + password);

        $.ajax({

                url: "/Account/LogOn",
                type: "POST",
                //data: JSON.stringify(data),
                //contentType: 'application/json; charset=utf-8',

                success: function (result) {

                    alert("Hello");
                    $("#div-2").empty();
                    $("#div-2").html(result).hide().fadeIn(300);
                }
        });

    });
    // Ajax call POST for login form button

It is not working 2 problems

  1. everytime that I click on the 'Connexion' button, The post controller is fired (I supposed from the @html.Beginform of the _Logon Partial View) and not from the Ajax Jquery

As a result, the partialView is displayed on a new internet page instead of displaying within the Div-2

  1. I want to update the Div-2 with a return partial view in case of the login/password check failure, but how can I tell the action controller to send me back a result in Json for ajax Jquery if login/password ok instead of a partial view ?

Thank you

3

3 Answers

1
votes

Ok one Question at a time

  1. use '@Url.Action("ActionMethodName", "ControllerName")' in url: field, the one done by you is not accurate.
  2. coming to second question thats simple just use dataType: "json" in your ajax code block after data: , that makes sure you can return json as result instead of partial view
0
votes

Is there any reason why you aren't using Ajax.BeginForm instead of Html.BeginForm? You should be able to do something like this:

@using (Ajax.BeginForm("LogOn", "Account", new AjaxOptions { UpdateTargetId = "div-2", OnBegin = "hideMessage", OnSuccess = "fadeInMessage" }))

Where hideMessage and fadeMessage are JS functions to hide and fade in your div.

0
votes

you should hook the submit event of form rather than click event of button and in submit handler you have to tell the browser not to go for normal post back by simply returning false or using preventDefault() like

    $('form').live('submit',function(ev){
    ev.preventDefault();//to stop normal form post
    var email = $("#div-2 #Email").val();
            var password = $("#div-2 #Password").val();

            var data = { Email: "hello", Password: password };

            alert(email + password);

            $.ajax({

                    url: "/Account/LogOn",
                    type: "POST",
                    data: JSON.stringify(data),
                    contentType: 'application/json; charset=utf-8',
                    dataType:'json',

                    success: function (result) {

                        alert("Hello");
                        $("#div-2").empty();
                        $("#div-2").html(result).hide().fadeIn(300);
                    }
            });
//return false; you can simply uncomment this line and remove ev.preventDefault() to get same result

    });