Home > OS >  is it possible to pass route value using Ajax form submit?
is it possible to pass route value using Ajax form submit?

Time:02-28

The question: how to pass route value to the controller along with the form using Ajax?

I normally submit form using Ajax like this

        function AjaxFormSubmit(frm) {
            var form = `#${frm}`;
            $(form).submit(function (e) {
                e.preventDefault(); 
                var actionUrl = $(form).attr('action');

                $.ajax({
                    type: "POST",
                    url: actionUrl,
                    processData: false,
                    contentType: false,
                    data: $(form).serialize(), 
                    success: function (data) {
                        alert(data); 
                    }
                });
            });
        }

Usage :

        <button onclick="AjaxFormSubmit('formName')" >Create</button>

The form itself

   <form id="formName" asp-action="Create" asp-route-id="somedata">
    .... some fields

Then I get the form submitted successfully but I never get the route value asp-route-id

I recive it in the C# controller side like this

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(TheModel modelName, [FromQuery]string id)
    {
        ......
        return Json(id);
    }

or ... [FromRoute]string id

none of them is working

I get an empty white page with the value null !!

finally, how to pass route value to the controller along with the form using Ajax?

CodePudding user response:

Basically, if we want to use form to submit data to our server, we write your code like this, but not integrate ajax, in my code snippet, I added 2 buttons, one is using form data submit, another used ajax to send data:

enter image description here

    @model TestFormModel

<div >
    <div >
        <form method="post" id="formName" asp-action="CreateAction" asp-route-id="somedata">
            <div >
                <label asp-for="prop1" ></label>
                <input asp-for="prop1"  />
            </div>
            <div >
                <label asp-for="prop2" ></label>
                <input asp-for="prop2"  />
            </div>
            <div >
                <input type="submit" value="Create"  />
            </div>
        </form>
         <button onclick="AjaxFormSubmit('formName')" >CreateByAjax</button>
    </div>
</div>
<script>
    function AjaxFormSubmit(frm) {
        var form = `#${frm}`;
        console.log($(form).serialize());
        $.ajax({
            type: "POST",
            url: "https://localhost:44385/home/CreateAction",
            data: {
                prop1:$("#prop1").val(),
                prop2:$("#prop2").val(),
                id:"somedata"
            }, 
            success: function (data) {
                alert(data); 
            }
        });
    }
</script>

adding console log and we can see that there's no id property in the form.

  • Related