Alon Shmiel
Alon Shmiel

Reputation: 7121

send an object from javascript to the View

I have a variable is named: myvariable that has some elements (id, name, etc)

in my controller, I calculate some elements of this variable and return it: return View(myvariable).

I have another function in my controller:

public void drawnFromDb(id) {
    myclass myvariable;
    if (id == "1") {
        myvariable.text = "hello";
    }
    else {
        myvariable.text = "world";
    }
}

in my javascript function, I calculate the others elements:

function mydrawnFromDb(id) {
      $.ajax({
          type: "POST",
          url: baseUri + "mycontroller/drawnFromDb",
          data: { id: id },
          success: function () {

          },
          error: function (error) {

          }
      });
}

but I need to "return" myvariable to the view.

how can I do it please?

any help appreciated!

Upvotes: 0

Views: 61

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

Just return a JsonResult from the controller action, not void:

public ActionResult drawnFromDb(id) {
    myclass myvariable;
    if (id == "1") {
        myvariable.text = "hello";
    }
    else {
        myvariable.text = "world";
    }

    return Json(myvariable);
}

and in your success callback you can access the result:

success: function (result) {
    alert(result.text);
}

Upvotes: 2

aquaraga
aquaraga

Reputation: 4168

Return myVariable from the controller as a json:

        var javaScriptSerializer = new JavaScriptSerializer();
        var jsonObject = javaScriptSerializer.Serialize(myVariable);
        return jsonObject;

Now, you could use it in the ajax function:

function mydrawnFromDb(id) {
  $.ajax({
      type: "POST",
      url: baseUri + "mycontroller/drawnFromDb",
      data: { id: id },
      success: function (myVariableJson) {
         //Use the myVariableJson, and access the text property
      },
      error: function (error) {

      }
  });
}

Upvotes: 1

Related Questions