MVC View - JSON not parsing correctly from controller - c#

I am unable to understand why my JSON is not parsing correctly. I am parsing a c# dictionary to a JSON string in my controller. The output is correct there. When I pass the string back to my partial view, it does not render properly, and I am getting "Unexpected Token &" Ive tried it multilple ways in returning it to the view, but to no avail.
View:
var data = #Model.JSONDict
//data output - var data = {"3/1/2014":2,"2/28/2014":1,"2/27/2014":1,"2/26/2014":0,"2/25/2014":0,"2/24/2014":0,"2/23/2014":0}
//var keys = Object.keys(data);
Controller:
string output = JsonConvert.SerializeObject(dict);
//Resulting Output = "{\"3/1/2014\":2,\"2/28/2014\":1,\"2/27/2014\":1,\"2/26/2014\":0,\"2/25/2014\":0,\"2/24/2014\":0,\"2/23/2014\":0}"
ViewData["allEntries"] = output;
model.JSONDict = output;
return PartialView("_Graph", model);
I have also tried parsing out the & acocording to this post: Cannot get data in a view after parsing json data from controller in asp.net mvc like so, but getting the same error message:
storejson= getJSonObject("#ViewBag.JsonData");
function getJSonObject(value) {
return $.parseJSON(value.replace(/"/ig, '"'));
}

The problem is that in the output the JSON is encoded. In order to deal with this you can use the #Html.Raw() like so :
var data = #Html.Raw(Json.Encode(#Model.JSONDict))
But be advised that using #Html.Raw() may cause some security issues so it must be used with caution.

Related

Marketo - Response of Bulk API serialization

I'm trying to use the Bulk Import API endpoint within Marketo to fetch the warnings and failures associated with a bulk job I created within Marketo.
The output of these jobs is stated as an ObservableOfInputStreamContent, yet the response of these endpoints returns a csv string (with header column), that's not a JSON object. To compound to this problem, we are using the generated swagger files with the swagger definition file provided by Marketo. These generated c# client side files have the ObservableOfInputStreamContent object, but it's an empty object. I'm not sure if this is intended, or a mistake on Marketo's side. The generated files will attempt to use Newtonsoft.Json.JsonConvert.DeserializeObject<ObservableOfInputStreamContent>(responseText, JsonSerializerSettings); to deserialize the API response to the ObservableOfInputStreamContent.
Generated code that deserializes the API response:
var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
var typedBody = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responseText, JsonSerializerSettings);
return new ObjectResponseResult<T>(typedBody, responseText);
}
catch (Newtonsoft.Json.JsonException exception)
{
var message = "Could not deserialize the response body string as " + typeof(T).FullName + ".";
throw new ApiException(message, (int)response.StatusCode, responseText, headers, exception);
}
Problem one is that the API does not return JSON to begin with (eg):
address,city,country,
123 lane, new york, USA
745 street, new york, USA
This call will return this error because of this:
Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: a. Path '', line 0, position 0.
The second issue is that ObservableOfInputStreamContent is defined as an empty object to begin with in the generated files. So if the API response was valid JSON, I don't think it would know how to convert to that empty ObservableOfInputStreamContent object. The good news about the generated code is that it gives me an option to extend the ObservableOfInputStreamContent because it's defined as a partial class.
[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.1.11.0 (Newtonsoft.Json v11.0.0.0)")]
public partial class ObservableOfInputStreamContent
{
}
That said, is there any possible way I can use the JsonSerializerSettings to get around this issue? Could I extended the ObservableOfInputStreamContent class to hold a string property and then create my own JsonConverter to convert the string returned from the API into the new ObservableOfInputStreamContent?

Getting exception while retrieving data from POST method?

I am getting an exception while reading the post data.
I get error on this line:
HttpContext.Current.Request.Form["UserID"].ToString();
And the error is :
System.Collections.Specialized.NameValueCollection.this[string].get
returned null.
In method I have put this code :
StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
string requestFromPost = reader.ReadToEnd();
and data comes in that properly like this:
{
"UserID": "1000",
"Password": "ABCD"
}
Why I am not getting value in this HttpContext.Current.Request.Form["UserID"].ToString()? I also tried Request.QueryString but no success here.
Where am I doing wrong? Any help or suggestion would be much appreciated. Thanks!
There is no Form on this request. For a request body to be interpreted as form data, it must:
have a content type of x-www-form-urlencoded
be actually formatted as form encoded values, i.e. UserID=foo&Password=bar
JSON content is JSON, it will not be interpreted as form-data.
Web API should already take care of this for you. Given an action method:
public void Action(Credentials credentials)
where the Credentials class looks something like:
public class Credentials
{
string UserID { get; set;}
string Password { get; set; }
}
You shouldn't have to do anything else to have the framework turn this incoming JSON data into an instance of Credentials and pass it to the action method. This is automatic unless you've done something strange that breaks the conventions that WebAPI expects.

Extracting values from an encoded post request

At the moment my web app accepts post request fine. But I'm trying to read all the properties that are passed through to the object and then resend that object with a couple of properties changed. I'm having trouble viewing the object properties. Usual JSON objects are sent as a string and I can see all the properties that sent. Is there a way to see all the properties of an encoded JSON object?
I've tried examples from How to Get the HTTP Post data in C#?
public ActionResult Post(object value)
{
string[] keys = Request.Form.AllKeys;
for (int i= 0; i < keys.Length; i++)
{
Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>");
}
return new HttpStatusCodeResult(200);
}
But I get a compiler error indicating that HttpRequestMessage does not contain a definition for 'Form'.
I also tried Request.Form["payload"]; or Request["payload"] then i am presented with the error Cannot applying indexing to an expression of type 'HttpRequestMessage'
I would like to know the properties that are sent before I create the class. Do I have to create the class first then cast it to the object?
System.Web.HttpContext.Current.Request.Form
this can help you to access Form information in anywhere.
no matter ApiController or anything else
actually for webform and MvcController you can directly access Request.Form, but not in ApiController

Output JSON value in ASP.NET MVC

I´m trying to get single value out of an object array and display it for now inside paragraph tag on my index page.
In my HomeController I have done this
public ActionResult Index()
{
WebClient client2 = new WebClient();
Stream stream = client2.OpenRead("http://localhost/ARN/weatherAPI.json");
StreamReader reader = new StreamReader(stream);
Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine());
// instead of WriteLine, 2 or 3 lines of code here using WebClient to download the file
var weatherString = (string)jObject["weather"][0]["main"];
stream.Close();
return View();
I started by creating a new project in Console Application to test it and I ran this lines of code but used Console.Writeline(weatherString) and it gave me exactly the value I needed in the console but now I'm facing the problem to try to show it on the index page with the ASP.NET MVC
Since this piece of code is in my HomeController and my Index.cshtml is elsewhere, is there an easy way for me to output the weatherString variable as an simple text on my index page?
The JSON looks like this:
"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}]
So I wan't "Rain" to be outputted on my webpage.
You'll probably want it in your ViewBag. In the controller:
ViewBag.WeatherString = weatherString;
then in the view access it with #ViewBag.WeatherString
Alternatively you can use it as the view's model:
return View(weatherString)
and in your view:
model string
but thats pretty overkill

Asp.Net Mvc - Don't clear error input in form

When I validate a form with Asp.Net Mvc and there's an error on the form, Asp.Net return me the form with the correct error message but clear the content of the input. I would like the content of the input to stay even if this content is wrong. How can I do that ?
UPDATE
Maybe this is because I don't use the default validation. I use the Fluent Validation library.
Here what I do :
var validator = new UserValidator();
var results = validator.Validate(user);
results.AddToModelState(ModelState, "");
if (!ModelState.IsValid)
{
return View("SignUp", user);
}
The problem might be in how you "bind" the model you are passing in the view. If you use a strongly typed view and create the input fields with for example
<%=Html.TexboxFor(m=>m.UserName)%>
or
<%=Html.TextBox("UserName", Model.UserName)%>
then you should see the values after posting.
Regards
In addition to what #Germán Ubillos posted, you can also store the post values in TempData and send them back through.
<%=Html.TextBox("UserName", TempData["UserName"])%>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SomeAction(string UserName)
{
TempData["UserName"] = UserName;
// Do your validation
var validator = new UserValidator();
var results = validator.Validate(user);
results.AddToModelState(ModelState, "");
if (!ModelState.IsValid)
{
return View("SignUp", user);
}
//return some view
}

Categories

Resources