Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return multiple variables with jsonresult asp.net mvc3

How to return multiple variables on JsonResult method

for example i want to return this two variables:

string result = "Successed";
string ID = "32"

I know how to return only one string:

return Json("Inserted");
like image 918
Irakli Lekishvili Avatar asked May 15 '12 15:05

Irakli Lekishvili


4 Answers

 public ActionResult YourAction()
 {
   var result=new { Result="Successed", ID="32"};
   return Json(result, JsonRequestBehavior.AllowGet);
 }

EDIT : As per the comment "How to get this data in client"

You can use getJSON from view to get this data like this

$(function(){
   $.getJSON('YourController/YourAction', function(data) {
      alert(data.Result);
      alert(data.ID);
   });
});

Make sure you have jQuery loaded in your view for this code to work.

like image 127
Shyju Avatar answered Oct 20 '22 08:10

Shyju


Return an anonymous object.

return Json( new { Result = result, Id = ID } );

I normally do something like this:

public enum NoticeTypes
{
    Default,
    UpdateComplete,
    ResponsePending,
    Notice,
    Error,
    Redirect,
    WaitAndRetryAttempt
}
public class AjaxJsonResponse
{
    public UserNotice Notice { get; set; }
    public object Data { get; set; }
    private AjaxJsonResponse() { }
    public static JsonResult Create(UserNotice Notice,object Data)
    {
        return new JsonResult()
        { 
            Data = new 
            { 
                Notice = Notice,
                Data = Data
            } 
        };
    }
}

So that I can write my javascript to always expect ajax calls to return data in a certain format.

return AjaxResponse.Create(NoticeTypes.UpdateComplete, new 
{ 
    Result = result, 
    Id = ID 
});

Now you can do things like an Ajax Complete global handler that can intercept things like Redirect or WaitAndRetry before the normal handler gets it, and to have a standard way of communicating additional information about the returned data that is the same across your application.

like image 21
asawyer Avatar answered Oct 20 '22 07:10

asawyer


On your controller use something like this:

var result = new { data= stuff, data2 = otherstuff };
return Json(result, JsonRequestBehavior.AllowGet);

If you are using .ajax() on your JavaScript you can use your data acessing like this:

$.ajax(
            {
                url: '/Controller/Method/',
                type: 'POST',
                data: 'data=' + data,
                success: function (result) {
                    $('#id').html("");
                    $(result.data).appendTo('#id');
                    $('#id2').html("");
                    $(result.data2).appendTo('#id2');
                    $('#id').show();
                    $('#id2').show();
                }
            });
like image 3
m0g3 Avatar answered Oct 20 '22 07:10

m0g3


1. Return as collection inside anonymous type This is the java script/ajax call and the complete html.

< script type = "text/javascript" >
  $(document).ready(function() {
    $("#ddlProduct").hide();
    $("#ddlRegion").change(function() {
      $("#ddlProduct").show();
      $("#ddlProduct").empty();
      $.ajax({
        type: "Post",
        url: "@Url.Action("
        GetProducts ")",
        dataType: "Json",
        data: {
          id: $("#ddlRegion").val()
        },
        success: function(jsonData) {
          console.log($(jsonData).length);
          if ($(jsonData.ProductList).length == 0) {
            $("#divProduct").hide();
          } else {
            $("#divProduct").show();
          }

          $.each(jsonData.ProductList, function(i, Product) {
            $("#ddlProduct").append('<option value=" ' + Product.Value + ' ">' + Product.Text + '</option>');
          });
          if ($(jsonData.FlavourList).length == 0) {
            $("#divFlavour").hide();
          } else {
            $("#divFlavour").show();
            $.each(jsonData.FlavourList, function(i, flavour) {
              $("#ddlFlavour").append('<option value=" ' + flavour.Value + ' ">' + flavour.Text + '</option>');
            });
          }
        },
        error: function(ex) {
          alert("Failed to return Products <br/>");
        }
      });
      return false;
    })
  }); //Document Ready Ends
< /script>
@{ ViewBag.Title = "Products Drop Down Demo"; }

<h2>Products Drop Down Demo</h2>
@using (Html.BeginForm()) {
<div>@Html.Label("Select Region:")</div>
<div class="editor-field">
  @if (ViewData.ContainsKey("Region")) { @Html.DropDownList("ddlRegion", ViewData["Region"] as List
  <SelectListItem>) }
</div>
<div id="divProduct" hidden="hidden">
  <br />
  <div>
    Select a Product:
  </div>
  <div>
    @Html.DropDownList("ddlProduct", new SelectList(string.Empty, "Value", "Text"), "Please select a Product", new { style = "width:250px", @class = "dropdown1" })
  </div>
</div>
<div id="divFlavour" hidden="hidden">
  <div>
    <br />Select a Flavour:
  </div>
  <div>
    @Html.DropDownList("ddlFlavour", new SelectList(string.Empty, "Value", "Text"), "Please select a Flavour", new { style = "width:250px", @class = "dropdown1" })
  </div>
</div>
}

This is the controller action that returns the data I tested and it is working.

               public ActionResult LoadRegion()
    {
        List<SelectListItem> Regions = new List<SelectListItem>();
        Regions.Add(new SelectListItem { Text = "Select A Region", Value = "0" });
        Regions.Add(new SelectListItem { Text = "Asea", Value = "1" });
        Regions.Add(new SelectListItem { Text = "Australia", Value = "4" });
        Regions.Add(new SelectListItem { Text = "America", Value = "5" });
        Regions.Add(new SelectListItem { Text = "Europe", Value = "6" });
        ViewData["Region"] = Regions;
        return View();
    }

public JsonResult GetProducts(string id) { List products = new List(); List flavours = new List();

        products.Add(new SelectListItem { Text = "Select Product", Value = "0" });
        products.Add(new SelectListItem { Text = "Cheese", Value = "1" });
        products.Add(new SelectListItem { Text = "Sause", Value = "2" });
        products.Add(new SelectListItem { Text = "Veberage", Value = "3" });
        products.Add(new SelectListItem { Text = "Snacks", Value = "4" });

        flavours.Add(new SelectListItem { Text = "Select Flavour", Value = "0", Selected = true });
        flavours.Add(new SelectListItem { Text = "Sweet", Value = "1" });
        flavours.Add(new SelectListItem { Text = "Sour", Value = "2" });
        flavours.Add(new SelectListItem { Text = "Spicy", Value = "3" });

        var myResult = new
        {
            ProductList = products,
            FlavourList = flavours
        };
        return Json(myResult, JsonRequestBehavior.AllowGet);

}

Let me know if you have any issue running this code. Thanks Premjeet

like image 2
user2449131 Avatar answered Oct 20 '22 08:10

user2449131