简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM