Search code examples
c#asp.net-mvc-4model-view-controllerorchardcms

Call controller function from ajax returns “__RequestVerificationToken” is not present(orchard) mvc


I am new at the Orchard,but I understand that it is like mvc.

I have some forms and buttons, I don't wont to use

@*@using (Html.BeginForm("UploadImage1","FileUpload", FormMethod.Post))
{
<input type="submit" value="Save to DataBase" id="btn_UploadImg" onclick="btn_Upload_Click()" />
}

To catch my event on server,I want to use onclick and then use ajax to call my controller function.

Here is my Html UPDATED:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
      <script......</script>

    </head>

    <body>

        <!-- form goes here -->

        <div class="container">
            <section id="content">

                    <form action="">
                   @Html.AntiForgeryToken()
                        <h1>Files Upload Form</h1>

   <input type="submit" value="Save" id="btn_UploadImg" onclick="btn_Upload_Click()" />
                    </form>

            </section><!-- content -->
        </div><!-- container -->

    </body>

My JavaScript Updated:

    function btn_Upload_Click() {

       var token = $('input[name="__RequestVerificationToken"]').val();

$.ajax({
    url: '@Url.Action("UploadImage2", "FileUpload")',
    type: 'POST',
    data: {
        sNum: "123",
        "__RequestVerificationToken": token
    },
    traditional: true,
    success: function () {
    },
    error: function (xhr) {
        alert(xhr.responseText);

    }
});

    }

And my controller

namespace VnModule.Module.Controllers
{
    public class FileUploadController : Controller
    {

     [HttpPost]
    [ValidateAntiForgeryToken]
    public void UploadImage1(string sNum)
    {
        int myNumber = Int32.Parse(sNum);

    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public void UploadImage2(string sNum)
    {
        int myNumber = Int32.Parse(sNum);


    }


    }
}

I am getting this error: "__RequestVerificationToken" is not present.

What am I doing wrong?


Solution

  • This problem is resolved by lzzy .I have Updated the code.

    To resolve this you need to do this:

    1.Add @Html.AntiForgeryToken() inside of your form were is your button is located.

       <form action="">
      @Html.AntiForgeryToken()
      <input type="submit" value="Save" id="btn_UploadImg" onclick="btn_Upload_Click()" />
                </form>
    

    2.In your ajax add to data parameter __RequestVerificationToken with value of

    $('input[name="__RequestVerificationToken"]').val();
    

    like this

     data:{
       sNum: "123",
      __RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
         }
    

    lzzy feel free to post your answer here,i will accept it,and remove my.