user1086355
user1086355

Reputation: 1333

To pass whole JSON objects into controller of MVC

I wants to pass whole JSON objects into controller in MVC so that i can access whole object. I am using following code ..

Script called in View

var Email = {
            To:  $("#txtTo").val(),
            Text:  $("#txtTest").val(),
            Subject: $("#txtSubject").val()
        };

        $.ajax({
            type: "POST",
            url: ("Controller/SendEmail"),
            data: JSON.stringify(Email ),
            datatype: "json",
            contentType: "application/json; charset=utf-8",
            cache: false,
            success: function(htmlResult) {
                alert("Mail Send")
            },
            error: function(msg) { alert("Error Occurs."); }
        });

but when i call this in controller :

 public ActionResult SendEmail(Model model)
            {
                string to = model.To ;
    }

it gives null. How to resolve this?

Upvotes: 1

Views: 953

Answers (2)

Dewasish Mitruka
Dewasish Mitruka

Reputation: 2896

You have to make a class like this :

public class ObjectFilter : ActionFilterAttribute
        {
            public string Param { get; set; }
            public Type RootType { get; set; }

            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json"))
                {
                    object o = new System.Runtime.Serialization.Json.DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);
                    filterContext.ActionParameters[Param] = o;
                }
            }
        }

you Class that you wants to pass into JSON is as follow :

public class Email
        {
            public To{ get; set; }
            public string Subject { get; set; }
            public string Text { get; set; }
        }

Now to have to call this class as attributes in your controller as :

[ObjectFilter(Param = "model", RootType = typeof(Email))]
public ActionResult SendEmail(Email model)
            {
                string to = model.To ;
    }

This will give you desired result.

Upvotes: 0

David Hedlund
David Hedlund

Reputation: 129802

If you would just send data: Email, rather than its stringified representation, the modelbinder would be able to bind the parameters being passed, to the actions input parameter.

In that way, the data will be treated not through JSON.stringify but through $.param, which will give you a string as such:

To=abc&Text=xyz&Subject=123

Which is how parameters are always being posted to the server. This is equivalent, therefore, to passing one variable at a time. If the names of these parameters match property names in the input parameter object, the default model binder will try to populate that object with the posted data.

Upvotes: 1

Related Questions