简体   繁体   English

从View传递到Controller的字符串变量在Controller中始终以NULL到达

[英]String variable passed from View to Controller always arrive as NULL in Controller

I want to pass data from the View to the Controller with an Ajax call. 我想通过Ajax调用将数据从View传递到Controller。 The following simplified code passes NULL every time. 以下简化代码每次都会传递NULL。 Can someone suggest what I'm doing wrong please? 有人可以建议我做错了吗?

Index.cshtml: Index.cshtml:

<input type="submit" id="ajaxTestButton" value="Pass To Controller" />

@section scripts {
    <script type="text/javascript">

        var testData = "Fred";

        $("#ajaxTestButton").click(function () {
            $.ajax({
                type: "POST",
                dataType: "text",
                data: testData,
                contentType: "text/plain",
                url: '@Url.Action("ButtonTest", "Home")'
            });
    });
    </script>

HomeController.cs: HomeController.cs:

namespace TestingAjax.Controllers
{
    public class HomeController : Controller
    {
        [HttpPost]
        public void ButtonTest(string Name)
        {
            // Do something interesting here.
        }

        public IActionResult Index()
        {
            return View();
        }
    }
}

I'm expecting string Name to be "Fred". 我期望字符串名称为“ Fred”。 Thank you. 谢谢。

Passing your json data using Formdata, Now you create GET and POST Action in controller. 使用Formdata传递json数据,现在您在控制器中创建GET和POST Action。

    <input type="submit" id="ajaxTestButton" value="Pass To Controller" />

@section scripts {
<script type="text/javascript">
        var formData = new FormData();
        formData.append("Name", "fred");

        $("#ajaxTestButton").click(function () {
        $.ajax({
            type: "POST",
            dataType: 'json',
            data: formData,
            processData: false,
            contentType: false,
            url: '@Url.Action("ButtonTest", "Home")'
        });
});
</script>
<input type="submit" id="ajaxTestButton" value="Pass To Controller" />

@section scripts {
    <script type="text/javascript">

        var testData = "Fred";

        $("#ajaxTestButton").click(function () {
            $.ajax({
                type: "POST",
                dataType: "text",
                data: { 'Name': testData },
                contentType: "text/plain",
                url: '@Url.Action("ButtonTest", "Home")'
            });
    });
    </script>

The recommended way is to serialize the form. 推荐的方法是序列化表格。

Keep in mind, in the controller action will be expecting your form type. 请记住,在控制器操作中将使用您的表单类型。 This is a great approach, if you have a form type MyViewModel that will be the type to be expected on the controller action. 如果您的表单类型为MyViewModel,它将是控制器操作上期望的类型,那么这是一种很好的方法。 All properties will be serialized and maped. 所有属性将被序列化和映射。

@section scripts {
    <script type="text/javascript">

        $("#ajaxTestButton").click(function () {
            var form = $('form');
        $.ajax( {
              type: "POST",
              url: form.attr( 'action' ),
              data: form.serialize(),
              success: function( response ) {
                console.log( response );
              }
            } );

    });
    </script>

In order to achieve your desired functionality using AJAX to POST your form variables to controller, refer to the following code snippet: 为了使用,以达到您想要的功能AJAXPOST表单变量控制器,请参考下面的代码片段:

<input type="submit" id="ajaxTestButton" value="Pass To Controller" />

@section scripts {
<script type="text/javascript">
        var yourName= "Fred";
        var json = {
                   Name: yourName
                   };

        $("#ajaxTestButton").click(function () {
        $.ajax({
            url: '@Url.Action("ButtonTest", "Home")',
            type: "POST",
            dataType: "json",
            data: { "json": JSON.stringify(json) },
            success: function (data) {
             //If there is no error from the server
             },
             error: function (data) {
             //If there is an error from the server
             },
        });
});
</script>

And in your controller, you can get your value like this: 在您的控制器中,您可以像这样获得价值:

using System.Web.Script.Serialization;
namespace TestingAjax.Controllers
{
    public class HomeController : Controller
    {
        [HttpPost]
        public void ButtonTest(string json)
        {
            var serializer = new JavaScriptSerializer();
            dynamic jsondata = serializer.Deserialize(json, typeof(object));
            //Get your Name variable here
            string name= jsondata["Name"];
            // Do something interesting here.
        }

        public IActionResult Index()
        {
            return View();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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