Illep
Illep

Reputation: 16851

Execute Jquery method from Razor Form

When I clicked on the submit button, it takes the form fields which are Email, Password and FName and executes the controller event instead of going through the jQuery method given below.

In the jQuery method I have edited the EMAIL address to be [email protected], However, in the controller I see the value that I entered in the Form Field. So, I think that my jQuery method hasn't been fired.

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

@Html.ValidationSummary()
<div class="form-group">
    @Html.LabelFor(m => m.EMAIL, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.EMAIL, new { id = "Email", @class = "form-control" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(m => m.PASSWORD, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.PasswordFor(m => m.PASSWORD, new { id = "pwd", @class = "form-control" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(m => m.Fname, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.PasswordFor(m => m.Fname, new { @class = "form-control" })
    </div>
</div>
<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" class="btn btn-default" value="Register" id="submitbuttonid"  />
    </div>
</div>

}

JQUERY

$(function () {
            $('submitbuttonid').click(function () {
                if ($(this).valid()) {
                    $.ajax({
                        url: '/Action/Register',
                        type: this.method,
                        data: {EMAIL : "[email protected]"},
                        success: function (result) {
                            $('#result').html(result);
                        }
                    });
                }
                return false;
            });
        });

CONTROLLER

    [AllowAnonymous]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterViewModel acc)
    {
        return RedirectToAction("Index", "Home");
    }

UPDATE

@using (Html.BeginForm(null,null,FormMethod.Post, new { id = "yourFormId" }))
{
    @Html.AntiForgeryToken()
    <strong>Hi </strong>
    @Html.Label("Text Content", new { id = "lastnamelbl" })
    @Html.Label("Text Content", new { id = "firstnamelbl" })
    <hr />
    @Html.ValidationSummary()
    <div class="form-group">
        @Html.LabelFor(m => m.EMAIL, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.EMAIL, new { id = "Email", @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.PASSWORD, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.PASSWORD, new { id = "pwd", @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Fname, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.Fname, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Register" id="submitbuttonid"  />
        </div>
    </div>

}

JS

 <script>


    $(function () {
        $('#yourFormId').on('submit', function (e) { //make it form submit event
            e.preventDefault(); // stop the form submission.
            if ($(this).valid()) {  // if form is valid, proceed with your ajax logic.
                // your current Code
                alert("jhjh");
                $.ajax({
                    url: '/Account/Register',
                    type: 'POST',
                    data: { EMAIL: "[email protected]" },
                    success: function (result) {
                        $('#result').html(result);
                    }
                });
            }
            return false;
        });
    });

UPDATE

<form action="/Account/Register/yourFormId" method="post"><input name="__RequestVerificationToken" type="hidden" value="poLluIrZEBZBe0Fr5QWfr5LoI4yrKn6Vc77gPYIE09RZc2qYvFxP3tNQ0UavJMc862RZ5Bd2vcEqKfmji39ktEnslbT38tKalIBeRD1la_U1" />  

Upvotes: 0

Views: 90

Answers (3)

user3559349
user3559349

Reputation:

Your POST method is decorated with [ValidateAntiForgeryToken] but your not passing the token so an exception is thrown on the server. Either remove the attribute, or pass it in the request, for example

$('form').submit(function() {
    if (!$(this).valid()) {
        return;
    }
    var token = $('[name=__RequestVerificationToken]').val();
    $.ajax({
        url: '@Url.Action("Register", "Account")', // don't hard code
        type: 'POST',
        data: { EMAIL: "[email protected]", __RequestVerificationToken: token},
        success: function (result) {
            $('#result').html(result);
        }
    });
    return false; / you do not need .preventDefault() when this is included
});

However, this means your not passing any of the other properties of your model so unclear what your trying to achieve with this. To serialize all the controls in the form, including the token, you can use

$('form').submit(function() {
    var formData = $(this).serialize(); // can always use formdata.EMAIL = newValue; to update it
    ....
    $.ajax({
        ....
        data: formData,

Upvotes: 0

Abdessalem MANAI
Abdessalem MANAI

Reputation: 59

The prameter EMAIL in ajax method is String type. So you have to declare the same name and same type in your C# method like this:

[AllowAnonymous]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(string  Email)
{
    return RedirectToAction("Index", "Home");
}

Upvotes: 0

Rajshekar Reddy
Rajshekar Reddy

Reputation: 18997

Problem: Is with the way your current code is,

$('submitbuttonid').click(function () { // You have a missing # in selector, Also this is click event of button
 if ($(this).valid()) { // $(this).valid() is always undefined, hence you ajax is never executed.
  // your current Code
 } 
return false;
});

Solution: Change the event to fire on form submit() rather than the button click

$('#yourFormId').on('submit',function (e) { //make it form submit event
 e.preventDefault(); // stop the form submission.
 if ($(this).valid()) {  // if form is valid, proceed with your ajax logic.
  // your current Code
 } 
return false;
});

Upvotes: 1

Related Questions