0

I'm very new to ASP.NET MVC and web development (I work mainly with c# and desktop development) and I have a big problem:

I try to pass data from my view to the controller, but everything I try ends up in an empty or null parameter in my controllers action...

I tried many approaches from different tutorials on the web but nothing worked, there must be something I am doing wrong in major.

I've created a simple project to demonstrate my problem:

My View:

@model TestJsonBinding.Models.TestModel


<body>
    @using (Html.BeginForm("TestTransfer", "Home", FormMethod.Post))
    {
        <p>Name: <input id="txbName" type="text" value="@Model.Name" /></p>
        <p>Alter: <input id="txbAge" type="number" value="@Model.Age" /></p>
        <p></p>
        <a id="btnSend" onclick="send()"> Send </a>
    }
</body>

<script>
    function send() {
        $.ajax({
            type: "POST",
            url: "TestTransfer",
            contentType: "application/json",
            data: GetModelJson(),
            success: function (result) {

            },
            error: function (result) {
                alert(result.text);
            }
        })
    }


    function GetModelJson() {
        var customModel = new Object();
        customModel.Name = $("#txbName").attr("value");
        customModel.Age = Number($("#txbAge").attr("value"));

        alert(JSON.stringify({ JsonDataTransfer: customModel }));

        return JSON.stringify({ JsonDataTransfer: customModel });
    }

</script> 

My controller:

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestJsonBinding.Models;

namespace TestJsonBinding.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new TestModel() { Name = "Parker", Age = 27});
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        [HttpPost]
        public ActionResult TestTransfer(TestModel model)
        {
            return Json(model);
        }

    }
} 

My model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TestJsonBinding.Models
{
    public class TestModel
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

That's the JSON my alert shows:

{"JsonDataTransfer":{"Name":"Parker","Age":27}}

and thats what I'm getting in the controller:

Screenshot

2 Answers 2

1

You don't need AJAX call to post the model to the controller action. Just submit the form. Instead of:

<a id="btnSend" onclick="send()"> Send </a>

Use:

<input type="submit" value="Send"/>

If for any reason you want to stick on AJAX, change your method like:

function GetModelJson() {
        var customModel = new Object();
        customModel.Name = $("#txbName").attr("value");
        customModel.Age = Number($("#txbAge").attr("value"));

        alert(JSON.stringify({ TestModel: customModel }));

        return JSON.stringify({ TestModel: customModel });
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. Yes I really need ajax. this is a testproject, the main project I need to get the model to the controller needs ajax at some points. I tried your changes with the json, but it is still not working. There must be some thing in major wrong with the project, i started a new asp.net mcv project and only editet the premade "Index.cshtml". Like yours, no excample from the internet worked for me. Is there a special .NET framework I should use to get this working? Currently I use 4.5.
0

First of all u needn't to wrap ur object to one more object. I mean ur alert should show:

{"Name":"Parker","Age":27}

For it simply change this line:

return JSON.stringify({ JsonDataTransfer: customModel });

To:

return JSON.stringify(customModel);

And change method sign to:

[HttpPost]
public ActionResult TestTransfer([FromBody]TestModel model)

2 Comments

Hello, thanks for the answer. I tried to test your approach but I can't add the needed namespace "using System.Web.Http;" so [FromBody] is not available. I use ASP.NET MVC with .NET 4.5
When I delete "TestModel :" from the parameters in stringify, then the call of my functrion "TestTransfer" don't work anymore

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.