Ajax没有将数据提交到后端MVVM C#。

huangapple go评论71阅读模式
英文:

Ajax Not Posting Data to Backend MVVM C#

问题

I am trying to post data from the front end HTML page to the backend code C# in a MVVM, I will either get a 404 or 400 error while making a lot of testing scenarios (usually the path).

Here is the JavaScript code:

$.ajax({
	type: 'POST',
	url: 'ReportModel/DepAct',
	data: JSON.stringify({ prop1: 'value1', prop2: 'value2' }),
	contentType: 'application/json; charset=utf-8',
	success: function (data) {
		alert('Data sent to backend!');
	},
	error: function (xhr, status, error) {
		alert('Data was not sent to backend!');
	}
});

And this is the backend:

public ActionResult DepAct(List<DepTB> selectedDep)
{
    // Process data as needed
    return new JsonResult(new { success = true });
}

I tried changing the path, data type, give different kinds of data in the front end and in the backend I tried to add different methods with different parameters like just a string, list based on a class, etc.

Update 1:

Modified the code to return the same data type and tested one of the answers but no luck

Javascript

var selectedDep = [{ prop1: "value1", prop2: "value2" }];
$.ajax({
    type: 'POST',
    url: '/Report/DepAct',
    data: JSON.stringify(selectedDep),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        alert('Data sent to backend!');
    },
    error: function (xhr, status, error) {
        alert('Data was not sent to backend!');
    }
});

Someone requested for the class as well

public class DepTB1
{
    public string prop1 { get; set; }
    public string prop2 { get; set; }
}

Method

public ActionResult DepAct([FromBody] List<DepTB1> selectedDep)
{
    // Process data as needed
    return new JsonResult(new { success = true });
}
英文:

I am trying to post data from the front end HTML page to the backend code C# in a MVVM, I will either get a 404 or 400 error while making a lot of testing scenarios (usually the path).

Here is the JavaScript code:

$.ajax({
	type: &#39;POST&#39;,
	url: &#39;ReportModel/DepAct&#39;,
	data: JSON.stringify({ prop1: &#39;value1&#39;, prop2: &#39;value2&#39; }),
	contentType: &#39;application/json; charset=utf-8&#39;,
	success: function (data) {
		alert(&#39;Data sent to backend!&#39;);
	},
	error: function (xhr, status, error) {
		alert(&#39;Data was not sent to backend!&#39;);
	}
});

And this is the backend:

public ActionResult DepAct(List&lt;DepTB&gt; selectedDep)
{
    // Process data as needed
    return new JsonResult(new { success = true });
}

I tried changing the path, data type, give different kinds of data in the front end and in the backend I tried to add different methods with different parameters like just a string, list based on a class etc.

Update 1:

Modified the code to return the same data type and tested one of the answers but no luck

Javascript

var selectedDep = [{ prop1: &quot;value1&quot;, prop2: &quot;value2&quot; }];
            $.ajax({
                type: &#39;POST&#39;,
                url: &#39;/Report/DepAct&#39;,
                data: JSON.stringify(selectedDep),
                dataType: &quot;json&quot;,
                contentType: &quot;application/json; charset=utf-8&quot;,
                success: function (data) {
                    alert(&#39;Data sent to backend!&#39;);
                },
                error: function (xhr, status, error) {
                    alert(&#39;Data was not sent to backend!&#39;);
                }
            });

Someone requested for the class as well

public class DepTB1
    {
        public string prop1 { get; set; }
        public string prop2 { get; set; }
    }

Method

public ActionResult DepAct([FromBody] List&lt;DepTB1&gt; selectedDep)
        {
            // Process data as needed
            return new JsonResult(new { success = true });
        }

答案1

得分: 0

Your controller action parameter expecting list but you are sending single object which mismatched with method signature. Another important issue is you are missing [FromBody] because by default ajax request type is application/x-www-form-urlencoded but you are sending json data.

Assuming you have following class:

Model:

public class DepTB
{
    public string prop1 { get; set; }
    public string prop2 { get; set; }
}

Modify Ajax code:

var selectedDep = [{ prop1: "value1", prop2: "value2" }];

$.ajax({
    type: 'POST',
    url: '/ReportModel',
    data: JSON.stringify(selectedDep),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        alert('Data sent to backend!');
    },
    error: function (xhr, status, error) {
        alert('Data was not sent to backend!');
    }
});

Note: This would also be correct JSON.stringify([{ prop1: "value1", prop2: "value2" }])

Add [FromBody] In Controller:

public ActionResult OnPost([FromBody] List<DepTB> selectedDep)
{
    // Process data as needed
    return new JsonResult(new { success = true });
}

Output:

Ajax没有将数据提交到后端MVVM C#。

Note: You can get more details here in Jquery Official Document

Update:

Based on your shared link and description, it appeared that, you are using razor page. While sending ajax request within razor page it requires addition XSRF-TOKEN in header, you could add following code snippet within your ajax request:

Include XSRF-TOKEN in header:

headers: {
    RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
}

You can ignore antiforgery token:

You even can ignore forgery token by using [IgnoreAntiforgeryToken] before your razor page as following:

Page Model:

[IgnoreAntiforgeryToken]
public class ReportModel : PageModel
{
    public ActionResult OnPost([FromBody] List<DepTB> selectedDep)
    {
        // Process data as needed
        return new JsonResult(new { success = true });
    }
}

Ajax:

$.ajax({
    type: 'POST',
    url: '/ReportModel',
    data: JSON.stringify([{ prop1: "value1", prop2: "value2" }]),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    headers: {
        RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
    },
    success: function (data) {
        alert('Data sent to backend!');
    },
    error: function (xhr, status, error) {
        alert('Data was not sent to backend!');
    }
});

Output:

Ajax没有将数据提交到后端MVVM C#。

英文:

> I tried changing the path, data type, give different kinds of data in
> the front end and in the backend I tried to add different methods with
> different parameters like just a string, list based on a class etc.

Your controller action parameter expecting list but you are sending single object which mismatched with method signature. Another important issue is you are missing [FromBody] because by default ajax request type is application/x-www-form-urlencoded but you are sending json data.

Assuming you have following class:

Model:

public class DepTB
    {
        public string prop1 { get; set; }
        public string prop2 { get; set; }
    }

Modify Ajax code:

var selectedDep = [{ prop1: &quot;value1&quot;, prop2: &quot;value2&quot; }];


            $.ajax({
                type: &#39;POST&#39;,
                url: &#39;/ReportModel&#39;,
                data: JSON.stringify(selectedDep),
                dataType: &quot;json&quot;,
                contentType: &quot;application/json; charset=utf-8&quot;,
                success: function (data) {
                    alert(&#39;Data sent to backend!&#39;);
                },
                error: function (xhr, status, error) {
                    alert(&#39;Data was not sent to backend!&#39;);
                }
            });

Note: This would also be correct JSON.stringify([{ prop1: &quot;value1&quot;, prop2: &quot;value2&quot; }])

Add [FromBody] In Controller:

public ActionResult OnPost([FromBody] List&lt;DepTB&gt; selectedDep)
        {
            // Process data as needed
            return new JsonResult(new { success = true });
        }

Output:

Ajax没有将数据提交到后端MVVM C#。

Note: You can get more details here in Jquery Official Document

Update:

Based on your shared link and description, it appeared that, you are using razor page. While sending ajax request within razor page it requires addition XSRF-TOKEN in header, you could add following code snippet within your ajax request:

Include XSRF-TOKEN in header:

headers: {
          RequestVerificationToken: $(&#39;input:hidden[name=&quot;__RequestVerificationToken&quot;]&#39;).val()
         }

You can ignore antiforgery token:

You even can ignore forgery token by using [IgnoreAntiforgeryToken] before your razor page as following:

Page Model:

[IgnoreAntiforgeryToken]
public class ReportModel : PageModel
{
    public ActionResult OnPost([FromBody] List&lt;DepTB&gt; selectedDep)
        {
            // Process data as needed
            return new JsonResult(new { success = true });
        }
}

Ajax:

        $.ajax({
                type: &#39;POST&#39;,
                url: &#39;/ReportModel&#39;,
                data: JSON.stringify([{ prop1: &quot;value1&quot;, prop2: &quot;value2&quot; }]),
                dataType: &quot;json&quot;,
                contentType: &quot;application/json; charset=utf-8&quot;,
                headers: {
                    RequestVerificationToken:
                        $(&#39;input:hidden[name=&quot;__RequestVerificationToken&quot;]&#39;).val()
                },
                success: function (data) {
                    alert(&#39;Data sent to backend!&#39;);
                },
                error: function (xhr, status, error) {
                    alert(&#39;Data was not sent to backend!&#39;);
                }
            });

Ouput:

Ajax没有将数据提交到后端MVVM C#。

答案2

得分: 0

The code is working after adding OnPost in front of the method's name in the class

[ValidateAntiForgeryToken]
public IActionResult OnPostDepAct([FromBody] List<DepTB1> selectedDep)
{
    // Process data as needed
    return new JsonResult(new { success = true });
}

And using the following kind of URL in the JavaScript

var selectedDep = [{ prop1: "value1", prop2: "value2" }];
$.ajax({
    type: 'POST',
    url: '/Reports/Report?handler=DepAct',
    beforeSend: function (xhr) {
        xhr.setRequestHeader("XSRF-TOKEN",
            $('input:hidden[name="__RequestVerificationToken"]').val());
    },
    data: selectedDep,
    success: function (data) {
        alert('Data sent to backend!');
    },
    error: function (xhr, status, error) {
        alert('Data was not sent to backend!');
    }
});

Thanks all for trying!

英文:

The code is working after adding OnPost in front of the method's name in the class

[ValidateAntiForgeryToken]
        public IActionResult OnPostDepAct([FromBody] List&lt;DepTB1&gt; selectedDep)
        {
            // Process data as needed
            return new JsonResult(new { success = true });
        }

And using the following kind or URL in the Javascript

var selectedDep = [{ prop1: &quot;value1&quot;, prop2: &quot;value2&quot; }];
            $.ajax({
                type: &#39;POST&#39;,
                url: &#39;/Reports/Report?handler=DepAct&#39;,
                beforeSend: function (xhr) {
                    xhr.setRequestHeader(&quot;XSRF-TOKEN&quot;,
                        $(&#39;input:hidden[name=&quot;__RequestVerificationToken&quot;]&#39;).val());
                },
                data: selectedDep,
                success: function (data) {
                    alert(&#39;Data sent to backend!&#39;);
                },
                error: function (xhr, status, error) {
                    alert(&#39;Data was not sent to backend!&#39;);
                }
            });

Thanks all for trying!

huangapple
  • 本文由 发表于 2023年4月4日 16:41:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75927241.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定