Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to pass a "C#" object to a controller via AJAX?

It's simple enough to pass a string to a controller action via jQuery ajax, but is it possible to serialize a group of variables into an object, send it to the controller, and have the controller recognize it as an object?

For example:

In the server, you have a class Obj as such:

class Obj{
    string a; int b; double c;
}

And in the controller, you have a method that is expecting an Obj object

public JsonResult UpdateObj(Obj obj){
    //stuff
}

Is there a way in Jquery to serialize some JavaScript vars into a class Obj and then send it to an MVC controller action via an AJAX post?

like image 839
Jay Sun Avatar asked Jul 20 '11 18:07

Jay Sun


People also ask

Is there a pass in C?

Parameters in C functions There are two ways to pass parameters in C: Pass by Value, Pass by Reference.

What does passing mean in C?

1. Pass by value - it is same as c, actual values will not change, scope of this values are of function only. 2. Pass by Reference - actual values (Address of actual operands) are passed so it will change the values globally, it means if values gets changed then it will affect in whole program.

How do you pass a function in C?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.

Is there reference in C?

No, it doesn't. It has pointers, but they're not quite the same thing. For more details about the differences between pointers and references, see this SO question.


1 Answers

Sure, let's suppose that you have a strongly typed view:

@model Obj

<script type="text/javascript">
    // Serialize the model into a javascript variable
    var model = @Html.Raw(Json.Encode(Model));

    // post the javascript variable back to the controller 
    $.ajax({
        url: '/home/someAction',
        type: 'POST',  
        contentType: 'application/json; charset=utf-8',
        data: JSON.serialize(model),
        success: function(result) {
            // TODO: do something with the results
        }
    });
</script>

and in the controller action:

public ActionResult SomeAction(Obj obj)
{
    ...
}

Just a remark about this Obj, make it have public properties instead of some fields:

public class Obj
{
    public string A { get; set; }
    public int B { get; set; }
    public double C { get; set; }
}
like image 83
Darin Dimitrov Avatar answered Oct 03 '22 21:10

Darin Dimitrov