Home > OS >  assure that the controller method is actually called by ajax or by POST request in mvc
assure that the controller method is actually called by ajax or by POST request in mvc

Time:10-24

I was testing my code, passing the data from the view page to controller create method. I tried to pass the data using ajax, but how can I be assured that my controller method is really called by ajax function and not by POST request method.

When I change the url in ajax or pass wrong id values as input in ajax method, still the controller method is called and also getting back the response message back to the ajax function.

Let me show you my ajax code:

<script>
    $(document).ready(function () {
        $('#btn_submit').click(function () {

            var testModel = {
                FirstName: $('#First_Name').val(),
                LastName: $('#LastName').val(),
                Gender: $("input[name='Gender']:checked").val(),
                Contact: $('#Contact').val(),
                Faculty: $('#Faculty').val(),
                RegNepaliDate: $('#inp_date').val()
            };
            alert(JSON.stringify(testModel));

            $.ajax({
                type: 'POST',
                url: '@Url.Action("Edit", "TestModels")', /*"/TestModels/Create",*/
                data: JSON.stringify(testModel),
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                success: function (data) {
                    if (response.success) {
                        alert(response.responseText);
                    }
                },
                error: function (req, status, error) {
                    console.log(error);
                }
            })

        })
    })
</script>

In the above code, I have passed wrong url i.e., url: '@Url.Action("Edit", "TestModels")', correct url should be url: '@Url.Action("Create", "TestModels")' and also the id of FirstName (First_Name) and inp_date is mistake, still the correct controller method TestModels/Create is called and also getting back success response.

My controller method:

// POST: TestModels/Create        
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Create(TestModel testModel, string LastName, string RegNepaliDate)
        {
            if (ModelState.IsValid)
            {
                //return null;
                //db.TestModels.Add(testModel);
                //db.SaveChanges();
                //return Json("true", JsonRequestBehavior.AllowGet);
                return Json(new { success = true, responseText = "Your message successfuly sent!" }, JsonRequestBehavior.AllowGet);
            }

            //return Json("false", JsonRequestBehavior.DenyGet);

            return Json(new { success = false, responseText = "Error." }, JsonRequestBehavior.AllowGet);
        }

My submit button code in view page:

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
<div class="form-horizontal">
    <h4>TestModel</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    
    // input form

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" id="btn_submit" />
        </div>
    </div>
</div>
}

I was very surprised how this is possible, in tutorials they only show how to pass data from view to controller via ajax but they never show how to check whether its really an ajax call or POST request. Please explain me how to check this. Thank You!!!

CodePudding user response:

This is due to @using (Html.BeginForm()). due to this your ajax method did not work.

When you call BeginForm() without any parameters it defaults to using the same controller/action used to render the current page.

Please refer : (How does @Html.BeginForm() works?)

If you want to call the ajax method then remove Html.BeginForm() syntax

  • Related