Outputting Json with the Razor view engine - asp.net-mvc

I've got a dictionary<string,string> as part of my view model. What I'm trying to do is cycle this object and output it as a json object. My reason for this is so I can localise my client script files correctly.
The output for this needs to look something like
var clientStrings = {"test":"yay","goodBye":"Nah"};
Any ideas how to achieve this correctly.
Thanks in advance.

It's built into MVC. Just return Json(yourobject).

Considering you are on mvc 3 you'll have access to JavaScriptSerializer. You should be able to do the following:
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize((object)yourDictionary);
This will serialize your dictionary to json. You may want to do this in the controller before sending the ViewData to the view to render.

Also you can integrate the free Json.NET library within your code.
This library does not suffer the problems JavascriptSerializer has like the circular reference problem.
This is a sample using the library to output JSON from a controller action
public virtual ActionResult ListData() {
Dictionary<string, string> openWith = new Dictionary<string, string>();
openWith.Add( "txt", "notepad.exe" );
openWith.Add( "bmp", "paint.exe" );
openWith.Add( "dib", "paint.exe" );
openWith.Add( "rtf", "wordpad.exe" );
JsonNetResult jsonNetResult = new JsonNetResult();
jsonNetResult.Formatting = Formatting.Indented;
jsonNetResult.Data = openWith;
return jsonNetResult;
}
If you execute this action you will get the following results
{
"txt": "notepad.exe",
"bmp": "paint.exe",
"dib": "paint.exe",
"rtf": "wordpad.exe"
}
JsonNetResult is a simple custom wrapper class around the functionalities of the Json.NET library.
public class JsonNetResult : ActionResult
{
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public object Data { get; set; }
public JsonSerializerSettings SerializerSettings { get; set; }
public Formatting Formatting { get; set; }
public JsonNetResult() {
SerializerSettings = new JsonSerializerSettings();
}
public override void ExecuteResult( ControllerContext context ) {
if ( context == null )
throw new ArgumentNullException( "context" );
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty( ContentType )
? ContentType
: "application/json";
if ( ContentEncoding != null )
response.ContentEncoding = ContentEncoding;
if ( Data != null ) {
JsonTextWriter writer = new JsonTextWriter( response.Output ) { Formatting = Formatting };
JsonSerializer serializer = JsonSerializer.Create( SerializerSettings );
serializer.Serialize( writer, Data );
writer.Flush();
}
}
}

Related

How to return json date from MVC4 controller in ISO format

I tried tro return date in ISO format using Json.Net from ASP.NET MVC4 controller
public JsonResult Sales() {
var saleList = new List<Sale>();
...
var str = JsonConvert.SerializeObject(saleList);
return Json(str, JsonRequestBehavior.AllowGet);
}
public class Sale
{
public DateTime saledate { get; set; }
...
}
But it returns whole object json notation as single string.
How to return date in ISO format as json object ?
You can do it with ServiceStack JSON serializer but first you have to integrate it to ASP.NET MVC.
After installing the package, configure DateTime serialization in application start:
JsConfig.DateHandler = JsonDateHandler.ISO8601;
Create an ActionResult type for JSON content:
public class CustomJsonResult : ActionResult
{
private readonly object _data;
private readonly string _content;
private readonly Encoding _encoding;
public CustomJsonResult(object data) : this(data, null, null) { }
public CustomJsonResult(object data, string content) : this(data, content, null) { }
public CustomJsonResult(object data, Encoding encoding) : this(data, null, encoding) { }
public CustomJsonResult(object data, string content, Encoding encoding)
{
_data = data;
_content = content;
_encoding = encoding;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(_content) ? "application/json" : _content;
if (_encoding != null)
{
response.ContentEncoding = _encoding;
}
response.Write(JsonSerializer.SerializeToString(_data));
}
}
Then you can add these methods to a base controller:
protected CustomJsonResult CustomJson(object data)
{
return new CustomJsonResult(data);
}
protected CustomJsonResult CustomJson(object data, string content)
{
return new CustomJsonResult(data, content);
}
protected CustomJsonResult CustomJson(object data, Encoding encoding)
{
return new CustomJsonResult(data, encoding);
}
protected CustomJsonResult CustomJson(object data, string content, Encoding encoding)
{
return new CustomJsonResult(data, content, encoding);
}
At last you can return the result like this:
return CustomJson(saleList);
You can set settings when using an overload to SerializeObject that takes an JsonSerializerSettings parameter:
public static string SerializeObject(
Object value,
JsonSerializerSettings settings
)
The JsonSerializerSettings have a property called DateFormatHandlingused to distinguish between Microsoft Format and ISO format.
You could also use a custom converter in JSON.NET. Custom Converters can be applied using the CustomConverter attribute.
An example can be found in the JSON.NET documentation: http://james.newtonking.com/json/help/index.html
I would prefer the first possibility.

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

My problem is that I wish to return camelCased (as opposed to the standard PascalCase) JSON data via ActionResults from ASP.NET MVC controller methods, serialized by JSON.NET.
As an example consider the following C# class:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
By default, when returning an instance of this class from an MVC controller as JSON, it'll be serialized in the following fashion:
{
"FirstName": "Joe",
"LastName": "Public"
}
I would like it to be serialized (by JSON.NET) as:
{
"firstName": "Joe",
"lastName": "Public"
}
How do I do this?
or, simply put:
JsonConvert.SerializeObject(
<YOUR OBJECT>,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
For instance:
return new ContentResult
{
ContentType = "application/json",
Content = JsonConvert.SerializeObject(new { content = result, rows = dto }, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }),
ContentEncoding = Encoding.UTF8
};
I found an excellent solution to this problem on Mats Karlsson's blog. The solution is to write a subclass of ActionResult that serializes data via JSON.NET, configuring the latter to follow the camelCase convention:
public class JsonCamelCaseResult : ActionResult
{
public JsonCamelCaseResult(object data, JsonRequestBehavior jsonRequestBehavior)
{
Data = data;
JsonRequestBehavior = jsonRequestBehavior;
}
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public object Data { get; set; }
public JsonRequestBehavior JsonRequestBehavior { get; set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
}
var response = context.HttpContext.Response;
response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data == null)
return;
var jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
response.Write(JsonConvert.SerializeObject(Data, jsonSerializerSettings));
}
}
Then use this class as follows in your MVC controller method:
public ActionResult GetPerson()
{
return new JsonCamelCaseResult(new Person { FirstName = "Joe", LastName = "Public" }, JsonRequestBehavior.AllowGet)};
}
For WebAPI, check out this link:
http://odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx
Basically, add this code to your Application_Start:
var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
I think this is the simple answer you are looking for. It's from Shawn Wildermuth's blog:
// Add MVC services to the services container.
services.AddMvc()
.AddJsonOptions(opts =>
{
opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
Add Json NamingStrategy property to your class definition.
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
An alternative to the custom filter is to create an extension method to serialize any object to JSON.
public static class ObjectExtensions
{
/// <summary>Serializes the object to a JSON string.</summary>
/// <returns>A JSON string representation of the object.</returns>
public static string ToJson(this object value)
{
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter> { new StringEnumConverter() }
};
return JsonConvert.SerializeObject(value, settings);
}
}
Then call it when returning from the controller action.
return Content(person.ToJson(), "application/json");
Simpler is better IMO!
Why don't you do this?
public class CourseController : JsonController
{
public ActionResult ManageCoursesModel()
{
return JsonContent(<somedata>);
}
}
The simple base class controller
public class JsonController : BaseController
{
protected ContentResult JsonContent(Object data)
{
return new ContentResult
{
ContentType = "application/json",
Content = JsonConvert.SerializeObject(data, new JsonSerializerSettings {
ContractResolver = new CamelCasePropertyNamesContractResolver() }),
ContentEncoding = Encoding.UTF8
};
}
}
You must set the settings in the file 'Startup.cs'
You also have to define it in the default values of JsonConvert, this is if you later want to directly use the library to serialize an object.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(options => {
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
}
Below is an action method that returns a json string (cameCase) by serializing an array of objects.
public string GetSerializedCourseVms()
{
var courses = new[]
{
new CourseVm{Number = "CREA101", Name = "Care of Magical Creatures", Instructor ="Rubeus Hagrid"},
new CourseVm{Number = "DARK502", Name = "Defence against dark arts", Instructor ="Severus Snape"},
new CourseVm{Number = "TRAN201", Name = "Transfiguration", Instructor ="Minerva McGonal"}
};
var camelCaseFormatter = new JsonSerializerSettings();
camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
return JsonConvert.SerializeObject(courses, camelCaseFormatter);
}
Note the JsonSerializerSettings instance passed as the second parameter. That's what makes the camelCase happen.
In ASP.NET Core MVC.
public IActionResult Foo()
{
var data = GetData();
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
return Json(data, settings);
}
I did like this :
public static class JsonExtension
{
public static string ToJson(this object value)
{
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize
};
return JsonConvert.SerializeObject(value, settings);
}
}
this a simple extension method in MVC core , it's going to give the ToJson() ability to every object in your project , In my opinion in a MVC project most of object should have the ability to become json ,off course it depends :)
If you are returning ActionResult in .net core web api, or IHttpAction result then you can just wrap up your model in an Ok() method which will match the case on your front end and serialise it for you. No need to use JsonConvert. :)
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
this solve my problem

ViewModel in MVC correct way of accessing data

Can anyone please tell me whether this is the correct way of creating a viewmodel. I'm using Ninject and the only way I can get the view model to work is with the code below.
Also I cannot seem to be able to pass the data from the viewmodel to the controller unless I create a 2nd interface.
The code below does work, but reading all the examples I have seen I seem to be duplicating a lot off code from my domain layer.
---------------------Code Data access layer------
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace Web.Domain.SearchEngine
{
public class DisplaySearchResults
{
public string Title { get; set; }
public string Description { get; set; }
public string URL { get; set; }
}
public class GetSearchResults : IGetSearchResults
{
private string dbConn;
public GetSearchResults()
{
dbConn = ConfigurationManager.ConnectionStrings["Search"].ConnectionString;
}
public IEnumerable<DisplaySearchResults> SearchResults(string q, string option, int pagenumber)
{
List<DisplaySearchResults> Data = new List<DisplaySearchResults>();
string spName = "dbo.FTS_On_at_Websites";
using (SqlConnection cn = new SqlConnection(dbConn))
{
using (SqlCommand cmd = new SqlCommand(spName, cn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#strSearchPhrase", SqlDbType.VarChar, 100));
cmd.Parameters.Add(new SqlParameter("#SearchMode", SqlDbType.Int, 4));
cmd.Parameters.Add(new SqlParameter("#intPageNumber", SqlDbType.Int));
cmd.Parameters.Add(new SqlParameter("#intRecordsPerPage", SqlDbType.Int));
cmd.Parameters.Add(new SqlParameter("#intTotalRecordsReturned", SqlDbType.Int));
cmd.Parameters["#strSearchPhrase"].Value = q;
cmd.Parameters["#SearchMode"].Value = 1;
cmd.Parameters["#intPageNumber"].Value = pagenumber;
cmd.Parameters["#intRecordsPerPage"].Value = 10;
cmd.Parameters["#intTotalRecordsReturned"].Value = 10;
cn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.Default))
{
if (rdr.HasRows)
{
while (rdr.Read())
{
Data.Add(new DisplaySearchResults
{
Title = (string)rdr["PageTitle"],
Description = (string)rdr["PageParagraph"],
URL = (string)rdr["PageURL"]
});
}
}
return Data;
}
}
}
}
}
}
-------------Code ViewModel--------------------
using Microsoft.Security.Application;
using System.Collections.Generic;
using System.Linq;
using Web.Domain.SearchEngine;
namespace Web.UI.ModelHelpers.Search
{
public class DisplaySearchResultsViewModel
{
public string Title { get; set; }
public string Description { get; set; }
public string URL { get; set; }
}
public class GetSearchResultsViewModel : IGetSearchResultsViewModel
{
private readonly IGetSearchResults _IGSR;
public GetSearchResultsViewModel(IGetSearchResults IGSR)
{
_IGSR = IGSR;
}
public IEnumerable<DisplaySearchResultsViewModel> SearchResultsViewModel(string q, string option, int pagenumber)
{
var searchResults = _IGSR.SearchResults(q, option, pagenumber).AsEnumerable();
List<DisplaySearchResultsViewModel> GetData = new List<DisplaySearchResultsViewModel>();
foreach (var details in searchResults.AsEnumerable())
{
GetData.Add(new DisplaySearchResultsViewModel()
{
Title = Sanitizer.GetSafeHtmlFragment(details.Title),
Description = Sanitizer.GetSafeHtmlFragment(details.Description).ToLower(),
URL = Sanitizer.GetSafeHtmlFragment(details.URL),
});
}
return GetData;
}
}
}
In controller I have
var DisplaySearchResults = _IGSR.SearchResultsViewModel(cleanText, "1", 1);
No, this is not the correct way to build a view model. A view model should not contain any data access logic in it. That's the responsibility of the model.
What you should do instead is use Ninject to inject the IGetSearchResults instance into your controller instead of having your GetSearchResultsViewModel view model take it as constructor dependency. Actually you do not need this GetSearchResultsViewModel at all. You already have the correct view model called DisplaySearchResultsViewModel. Then it's the responsibility of your controller to use your data access layer and build this view model.
For example:
public class SomeController : Controller
{
private readonly IGetSearchResults repository;
public SomeController(IGetSearchResults repository)
{
this.repository = repository;
}
public ActionResult SomeAction(string q, string option, int pagenumber)
{
// query your data access layer and build the view model that you will
// pass to the view
IEnumerable<DisplaySearchResultsViewModel> model = this.repository
.SearchResults(q, option, pagenumber)
.AsEnumerable()
.Select(details => new DisplaySearchResultsViewModel
{
Title = Sanitizer.GetSafeHtmlFragment(details.Title),
Description = Sanitizer.GetSafeHtmlFragment(details.Description).ToLower(),
URL = Sanitizer.GetSafeHtmlFragment(details.URL)
})
.ToList();
return View(model);
}
}

Using the JSON.NET formatter for normal controllers

When returning Json from a controller (MVC 4 RC) I would like to modify the Json to use camel-casing for the properties and to do this I tried setting the GlobalConfiguration.Formatters.JsonFormatter (not sure if this is correct...don't have the code in front of me), but this does not appear to affect the Json outputted by the Controller.Json method.
After looking around it appears that this approach would only affect Web API controllers, etc. Is this true? Also, is it possible to alter the Controller.Json() method to acheive this?
Like #rouen suggests, created your own JsonDotNetResult.
This is the one I have in my project:
public class JsonNetResult : ActionResult
{
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public object Data { get; set; }
public int StatusCode { get; set; }
public JsonSerializerSettings SerializerSettings { get; set; }
public JsonNetResult()
{
SerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
var response = context.HttpContext.Response;
response.StatusCode = StatusCode;
response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType;
if ((StatusCode >= 400) && (StatusCode <= 599))
response.TrySkipIisCustomErrors = true;
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Data == null)
return;
var formatting = Formatting.None;
#if DEBUG
formatting = Formatting.Indented;
#endif
var writer = new JsonTextWriter(response.Output) { Formatting = formatting };
var serializer = JsonSerializer.Create(SerializerSettings);
serializer.Serialize(writer, Data);
writer.Flush();
}
}
I then have my own baseController that I inherit from to give me JsonDotNet(object viewModel) type methods.
E.g.
protected JsonNetResult JsonNet(object data = null, int statusCode = (int)HttpStatusCode.OK, string contentType = null)
{
return new JsonNetResult
{
Data = data,
StatusCode = statusCode,
ContentType = contentType
};
}
protected JsonNetResult JsonNetForbidden()
{
return JsonNet(statusCode: (int)HttpStatusCode.Forbidden);
}
protected JsonNetResult JsonNetNotFound()
{
return JsonNet(statusCode: (int)HttpStatusCode.NotFound);
}
protected JsonNetResult JsonNetNoContent()
{
return JsonNet(statusCode: (int)HttpStatusCode.NoContent);
}
protected JsonNetResult JsonNetCreated(object data)
{
return JsonNet(data, (int)HttpStatusCode.Created);
}
protected JsonNetResult JsonNetReload()
{
return JsonNet(new { reload = true });
}
protected JsonNetResult JsonNetRedirect(string url = null, string contentType = null)
{
return JsonNet(new { redirectUrl = url }, contentType: contentType);
}
protected JsonNetResult JsonNetClientError(ErrorDictionary errors)
{
return JsonNet(new { Errors = errors }, (int)HttpStatusCode.BadRequest);
}
protected JsonNetResult JsonNetUnauthorized()
{
return JsonNet(null, (int)HttpStatusCode.Unauthorized);
}
protected JsonNetResult JsonNetFlashMessage(string message)
{
return JsonNet(new { flashMessage = message });
}
There is no way to alter behaviour of default JavaScriptSerializer afaik.
Personally, I use my own JsonDotNetResult (and shortcut method on my BaseController) for all json actions. Not only you can alter its settings in many ways, but the performance is MUCH better with JSON.NET - look here http://james.newtonking.com/archive/2008/10/27/json-net-3-5-beta-1-big-performance-improvements-compact-framework-support-and-more.aspx
Plus there are many little nice bonuses, like automatic resoulution of circular dependencies (always hit it in bigger projects) etc.
Invest your 5 minutes into own JsonDotNetResult, they will be very well spent.
According to asp.net MVC 3 sources (I don't have ones for the fourth version at hand, but it is very unlikely something was changed there) you can't do that.
Controller.Json uses new JsonResult, and JsonResult.ExecuteResult uses new JavaScriptSerializer directly.
Some time ago we were looking for some way to affect this behavior but found none.

Returning Json data from MVC controller

public ActionResult About()
{
List<Stores> listStores = new List<Stores>();
listStores = this.GetResults("param");
return Json(listStores, "Stores", JsonRequestBehavior.AllowGet);
}
Using the above code I am able to get the below result
[{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555","email":"abc#ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}},
{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454","email":"nfnf#ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}},
How would I able to get the result in below format?
{
"stores" : [
{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555","email":"abc#ac.com",
"geo":{"latitude":"12.9876","longitude":"122.376237"}},
{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454","email":"nfnf#ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}} ]
}
I would like to have the stores at the beginning of the data.
Please help me in this regard.
You will need to create an object that contains the stores within a property named stores:
public ActionResult About()
{
var result = new { stores = this.GetResults("param") };
return Json(result, "Stores", JsonRequestBehavior.AllowGet);
}
I've used an anonymous type for simplicity here, if this result type were required in multiple places you may consider creating a 'proper' class for it.
JavaScriptSerializer can be found from namespace System.Web.Script.Serialization
var ser = new JavaScriptSerializer();
var jsonStores = ser.Serialize(stores);
return Json(new { stores: jsonStores }, "Stores", JsonRequestBehavior.AllowGet);
if you want to send object to client side as Json format
like Data-table,List,Dictionary etc. then need to override jsonResult and ExecuteResult
other wise use linq format to return data
like
using JSON.NET(must need to use override jsonResult and ExecuteResult )
DataTable dt = new DataTable();//some data in table
return json("data",JsonConvert.SerializeObject(dt))
other option using linq
var Qry = (from d in dt.AsEnumerable()
select new
{
value = d.Field<int>("appSearchID"),
text = d.Field<string>("appSaveSearchName"),
type = d.Field<int>("appSearchTypeStatus")
});
return json("Data", Qry);
override methods
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
try
{
return new JsonNetResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior,
MaxJsonLength = int.MaxValue
};
}
catch (Exception)
{
throw;
}
}
public class JsonNetResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
try
{
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
if (this.ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;
if (this.Data == null)
return;
using (StringWriter sw = new StringWriter())
{
response.Write(this.Data);
}
}
catch (Exception)
{
throw;
}
}
}
public class StoresViewModel{
public List<Stores> stores {get;set;}
}
public ActionResult About()
{
List<Stores> listStores = new List<Stores>();
listStores = this.GetResults("param");
StoresViewModelmodel = new StoresViewModel(){
stores = listStores;
}
return Json(model, JsonRequestBehavior.AllowGet);
}

Resources