mohsinali1317
mohsinali1317

Reputation: 4425

Html.BeginForm() in Razor Form ASP.NET

The issue is that the form submission event is triggered but the relevant action isn't being called. Do I have to mention the action name in the submit event of the form or will it figure it automatically?

Below you can see the code.

I am making a form like this

    @using (Html.BeginForm())
    {

        <div class="row">
            <div class="large-6 columns">
                <input type="text" placeholder="Meals per day" id="numOfMealsPerDay" value="@Model.numberOfMeals" />
               <input type="hidden" name="myHiddenInput" id="myHiddenInput" value="@Model.Id" />
            </div>
        </div>
        <div class="row">
            <div class="large-6 columns">
                <button type="submit" class="button small" id="updateNumOfMeals">Submit</button>
            </div>
        </div>
    }

In my Jquery I am doing this

$('form').submit(function () {

    var numOfMealsPerDay = $('#numOfMealsPerDay').val();

    console.log("form submitted");

    if (numOfMealsPerDay != '' && numOfMealsPerDay > 0) {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                console.log(result);
            }
        });
    } else {
        alert('cannot be empty or less than 0');
    }


    return false;
});

In the controller I am doing like this

   [HttpPost]

    public ActionResult UpdateSettings()
    {

        Debug.WriteLine("1");
        return Content("Thanks", "text/html");
    }

Upvotes: 0

Views: 820

Answers (2)

Guffa
Guffa

Reputation: 700252

The action name is specified by the route that is handling the request. If you haven't specified any routes you will be using the default route that catches an url in the form /Controller/Action.

As you don't specify any action and controller in the BeginForm method, it will use the same action and controller as the current page. You can use View Source in the browser to check that the generated form tag has the correct URL in the action attribute.

If the page is for example /Meals/UpdateSettings then the form tags action attribute will be the same, so the page will be posted back to the same address but with the POST http method instead of GET.

For that URL the UpdateSettings action in the MealsController controller would be used.

Upvotes: 1

SmartDev
SmartDev

Reputation: 2862

Do I have to mention the action name in the submit event of the form or will it figure it automatically?

You don't have to specify it if the HttpPost action name is the same as the HttpGet one. If you have a different action name you have to specify it like this:

Html.BeginForm(string ActionName, string ControllerName)

You also have other 13 definitions than you can use if you need to specify additional details (route values, method, html attributes, etc...)

Upvotes: 0

Related Questions