繁体   English   中英

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

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

我想通过Ajax调用将数据从View传递到Controller。 以下简化代码每次都会传递NULL。 有人可以建议我做错了吗?

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:

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

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

我期望字符串名称为“ Fred”。 谢谢。

使用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>

推荐的方法是序列化表格。

请记住,在控制器操作中将使用您的表单类型。 如果您的表单类型为MyViewModel,它将是控制器操作上期望的类型,那么这是一种很好的方法。 所有属性将被序列化和映射。

@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>

为了使用,以达到您想要的功能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>

在您的控制器中,您可以像这样获得价值:

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