I have a function that send a JSONResult, Now i want to use that function in C# and convert that JSONResult to IEnumerable so i can iterate on that result and pass that data to a SelectList function. Can i do this and how? Im using Asp.Net MVC, JQuery and C#
why not:
public myObject GetMyObject()
{
myRepository db = new myRepository();
return db.ListAllStuff();
}
public JsonResult GetMyJSON()
{
return Json(GetMyObject(), JsonRequestBehavior.AllowGet);
}
public List<SelectList> GetMyEnumerable()
{
return this.GetMyObject().ToList();
}
and you are reusing everything.
Also it can be done in this way.
var data = GetJsonResultData(); //call to JsonResult method.
var datastr = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(data.Data); // convert json object to string.
var dataclass = Newtonsoft.Json.JsonConvert.DeserializeObject<List<modeldto>>(datastr ); // string json data to class list
Related
Here is my code:
[HttpGet]
[Produces("application/json")]
[Route("whatever")]
public ActionResult<JsonResult> Get()
{
string jsonText = "{\"city\":\"paris\"}";
return new JsonResult(JObject.Parse(jsonText));
}
This is the output I want:
{"city":"paris"}
This is the output I get:
{"contentType":null,"serializerSettings":null,"statusCode":null,"value":{"city":"paris"}}
How can I change my code to prevent .NET framework from wrapping my original JSON?
Then use a simpler and strongly typed result object instead of trying to manually create the JSON string.
[HttpGet]
[Produces("application/json")]
[Route("whatever")]
public IActionResult Get() {
var model = new { city = "paris" };
return Ok(model);
}
the framework will serialize the model to the desired output
There is no problem with ASP.NET MVC's JsonResult, but you're using JSON.NET. In JSON.NET, when you convert an json string vi JObject.Parse(), it returns a JObject object that contains some members. If you want to get the converted json, you should use ToString(), as the following:
[HttpGet]
[Produces("application/json")]
[Route("whatever")]
public ActionResult<JsonResult> Get()
{
string jsonText = "{\"city\":\"paris\"}";
return new JsonResult(JObject.Parse(jsonText).ToString());
}
I am using TempData to allow error message to be displayed after a redirect. For compatibility, I am using a List<string> to add messages into a list of errors in NotificationHelper class:
if (TempData["errorNotification"] == null) {
TempData["errorNotification"] = new List<string> {
message
};
} else {
var data = (List<string>) TempData["errorNotification"];
data.Add(message);
TempData["errorNotification"] = data;
}
Inside the controller, I fill that TempData with an error message and before the return RedirectToAction() call, TempData contains a dictionary record with List<string> (To be exact: System.Collections.Generic.List`1[System.String]) as a value but right after the call, inside Terms() function, the value becomes an array (System.String[]).
[HttpGet]
public IActionResult Terms()
{
return View();
}
[HttpGet]
public IActionResult Index()
{
NotificationHelper.AddErrorNotification("error!", TempData);
return RedirectToAction("Terms");
}
The issue is that in order to use the data, I am casting the type in the view like so:
var errorMessages = TempData["errorNotification"] as List<string>;
and after the conversion I have to do this instead:
var errorMessages = TempData["errorNotification"] as string[];
One of above casts will come back as null, because of expecting a wrong type (depending on if I try to render the view before or after the redirect). Is that a desired behavior of TempData? How can I make sure that the view can expect one specific type being provided?
I ended up going with using IEnumerable, as #Stephen Muecke suggested since I was only looking for iterating over the data and not extending or changing it.
So in the view instead of trying to guess if it's a list or an array, I used IEnumerable to account for both:
var errorMessages = TempData["errorNotification"] as IEnumerable<string>;
Serialize your list of strings before assigning it to the TempData if you want to persist the type, and then deserialize it on retrieval. That's what I ended up doing. Though in my case I ended up storing a list of NotifyEntry instead of a list of string.
public class NotifyEntry
{
public NotifyType Type { get; set; }
public string Text { get; set; }
}
public enum NotifyType
{
Success,
Information,
Warning,
Error
}
I'm trying to send data as plain Json, from my controller to the client side of my MVC application. The data is initially collected as a list of objects but I'm having trouble converting it to straight Json. Right now the code in my controller is as follows:
[HttpGet]
public JsonResult SecurityPermissionsTableData()
{
List<SecurityPermissionsGridModel> list = securityPermissionsTable.Get(System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\').Last());
string json = JsonConvert.SerializeObject(new
{
data = list
});
return ResultJson(json);
}
public JsonResult ResultJson(object data)
{
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = data };
}
When I use the JsonConvert.SerializeObject() function, it returns a string:
"{\"data\":[{\"Username\":\"loganfg\",\"readbutton\":null,\"editbutton\":null,\"deletebutton\":null}]}"
However I need to return plain Json in the form of:
{"data":[{"Username":"lgilmore","readbutton":"<a onclick='SP_read(\"7\")' class='SRKbutton tiny SP_rbutton'>Details</a>","editbutton":null,"deletebutton":null}]}
How can I convert the string the serialize function returns to plain Json? Or how do I alter my ResultJson() function to properly handle and convert the string?
JsonResult already serializes the object for you.
Therefore, it's serializing your string to a JSON string literal.
You should get rid of all of your code and just
return Json(list, JsonRequestBehaviour.AllowGet);
You may simply use the Json method.
Pass the object you want to convert to json as the parameter.
public JsonResult SecurityPermissionsTableData()
{
var permissionList = securityPermissionsTable
.Get(System.Security.Principal.WindowsIdentity.GetCurrent()
.Name.Split('\\').Last());
return Json(permissionList , JsonRequestBehaviour.AllowGet);
}
I am trying to passing List to controller method using ajax. example I am 2 objects in the list like below. I am getting two objects in controller but inside properties are null
var dataObject = { 'sections': sectionsOrder};
console.log(dataObject);
CustomAjaxRequest("Post", "#Url.Action("UpdateOrderHoldingsForSections", "Renewal")" ,
dataObject, "json", "UpdateSectionsViewWithLatestOrderHoldings",
null, true);
[HttpPost]
public ActionResult UpdateOrderHoldingsForSections(List<OrderHoldings> sections)
{
return null;
}
even I tried var dataObject = { 'sections': json.stringify(sectionsOrder)}; still nothing working. What could be the problem?
In Console before passing values
Your controller is expecting a List, but you're passing up an object with a property that is a list. Try sending up the array directly, it should map to List
CustomAjaxRequest("Post", "#Url.Action("UpdateOrderHoldingsForSections", "Renewal")" ,
sectionsOrder, "json", "UpdateSectionsViewWithLatestOrderHoldings",
null, true);
Or you could instead add a C# binding model which has a property public List<OrderHoldings> Sections { get; set; }
Here is how I would do:
var jsonData = JSON.stringify(sectionsOrder);
var dataObject = { sections: jsonData };
CustomAjaxRequest("Post", "#Url.Action("UpdateOrderHoldingsForSections", "Renewal")" , dataObject, "json", "UpdateSectionsViewWithLatestOrderHoldings", null, true);
And then in controller,
[HttpPost]
public ActionResult UpdateOrderHoldingsForSections(string sections)
{
List<OrderHoldings> sectionsHoldings;
JavaScriptSerializer seriliazer = new JavaScriptSerializer();
sectionsHoldings = seriliazer.Deserialize<List<OrderHoldings>>(sections);
.
.
.
}
and yes, make sure that you are accepting string in the controller as seen above and not List
I am new to ASP.NET MVC and learning. So far I have figured out how I can create a JSON Object and return that as a response to a request. However, I'm not able to pass a JSON body as part of a POST request like I normally did using Java.
Here is the code how I did this there -
#Path("/storeMovement")
#POST
#Consumes("application/json")
#Produces("application/json")
public String storeTrace(String json) {
JSONObject response = new JSONObject();
JSONParser parser = new JSONParser();
String ret = "";
try {
Object obj = parser.parse(json);
JSONObject jsonObj = (JSONObject) obj;
RecordMovement re = new RecordMovement((double) jsonObj.get("longitude"), (double) jsonObj.get("latitude"), (long) jsonObj.get("IMSI"));
ret = re.Store();
// Clear object
re = null;
System.gc();
response.put("status", ret);
} catch (Exception e) {
response.put("status", "fail " + e.toString());
}
return response.toJSONString();
}
I tried the same in the ASP.NET Action method but the value in the string parameter a is null as seen while debugging. Here's the code for the Action method -
public string Search(string a)
{
JObject x = new JObject();
x.Add("Name", a);
return x.ToString();
}
It works fine when I use an Object (for example - Book) like so -
public string Search(Book a)
{
JObject x = new JObject();
x.Add("Name", a.Name);
return x.ToString();
}
In that case, the book's name gets de-serialized just fine as I would expect. The class definition for the Book class -
public class Book
{
public int ID { get; set; }
public string Name { get; set; }
}
Can somebody please advise what I'm doing wrong? Is there no way to take in a string and then de-serialize? I'd like to be able to take in JSON without having to use an Object
As for as understand you want pass entire of request body to a string without any binding so you could handle passed string data with your desired way.
To aim this purpose simply write your own model binder:
public class RawBodyBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if(typeof(string)!=bindingContext.ModelType)
return null;
using (var s = new StreamReader(controllerContext.HttpContext.Request.InputStream))
{
s.BaseStream.Position = 0;
return s.ReadToEnd();
}
}
}
And in you action method assign your binder to desired parameter:
public string MyAction([ModelBinder(typeof(RawBodyBinder))]string json)
{
}
But MVC has own JSON model binder as well if your data is a standard JSON and in request body with Content-Type: application/json header you could use MVC's JSON model binder to activate JSON model binder simply add following line in Global.asax.cs file:
protected void Application_Start()
{
// some code here
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}
The first thing in asp.net mvc to post a data is to decorate the method with this attribute [Httpost]
it's mean passing a string
should look like
[HttpPost]
public string Search(string a){
// your code
}
The default value is [HttpGet] that get parameters from url. For Post request you need to.
Edit:
And look the answer from vinayan
with jquery:
$.ajax({
method: "POST",
url: "Home/Search",
data: {'a': 'yourstring'}
})
The name of the parameter you send is used for the de-serialization. So in in this case, "a" should be part of json.
public string Search(string a)
so you will have to use,
$.ajax({
method: "POST",
url: "Home/Search",
data: {'a': 'yourstring'}
})