Pass HashTable to View from Controller in MVC 3 - c#

Is there a way to pass a HashTable loaded with key/values to a page View in a way I can then use it via javascript/Jquery ?
Example: I have HashTable with
key = Car Model (206 XT), Value = "PEUGEOT", etc...............
So in the view I have a combo with all car models and near that, I have a textbox automatically populated with the manufacturer taken from javascript
Is there a way to do so ??
(I'm really noob in MVC 3 :()

There are different way to solve this problem:
if you wan't to get this list dynamicaly with out reloading you can use a json request (examples).
Javascript:
$.ajax({
type: "POST",
url: "/controler/action",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (result){
for(var i=0; i<result.length; i++) {
var value = result[i];
alert(i =") "+value);
}
}
Controler (c#):
[HttpPost]
public JsonResult Action()
{
return Json(YourTable.ToArray());
}
Furthermore you can access every html-element from javascript. So you can put the content in all kinds of html-elements.

You can serialize most C# objects using the following method in the view:
<script type="text/javascript">
var hashtable = #Html.Raw(Json.Encode(Model.YourHashtable)
</script>
If you have some Tree like data structures with parent/child relationships you might run into issues as the Encoder can't solve circular relationships.

Related

View data from the database

this year I need to build a project on HTML
I choose to build a store so I build a database for all the items (i call it items)
every item has a logo(link to photo), name, price, and description.
and now I want to show all the items on the main page (every single item on an item card)
but! I need to show it Dynamically(That it will only show products that exist in the database)
I try to do it with function with response.write but it did not succeed...
If you can help it would be great!
Create web APIs of return Json type in MVC architecture with C# and include and display the Jquery library in the project.
Jquery library CDN link in;
https://code.jquery.com/jquery-3.6.0.min.js
Example backend code;
public JsonResult AllProduct()
{
var list = db.products.ToList(); //products name table
return Json(list, JsonRequestBehavior.AllowGet);
}
To connect with jquery in html page;
$.ajax({
type: "GET",
url: "AllProduct",
contentType: "application/json",
dataType: "json",
success: function(response) {
$("#table").html(response); //Example #table div show return all value
},
error: function(response) {
console.log(response);
}
});
The database is unknown so let me try to explain the logic. Let me give an example over MVC since you use c# and html tags by definition. In Razor view it will look like below
#foreach(var product in ProductList){
<div>
<div><img src="#product.logoImgConvertedToBase64" /></div>
<div>#product.name</div>
<div>#product.price</div>
<div>#product.description</div>
</div>
}

Json is not properly binded as c# object

My app is made in ASP.NET MVC 5. User can use search form which is displaying filtered data. Now I want to add button which will export displayed data.
To do this I am sending Search object to view and save it in html. Now When clicking export button I want to pass this object to controller, get data from database using this Search object and save results as text.
The thing is I cant bind json to c# object. Thats my view:
<div id="originalForm" style="visibility:hidden">
#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))
</div>
This is my ajax code:
function exportRaportToCsv() {
var $formData = $('#originalForm').text();
var allIds = getCheckedIds();
var dataToSend = JSON.stringify({
ids: allIds,
search: $formData
});
$.ajax({
type: "POST",
url: '#Url.Action("ExportToCsv", "BankCosts")',
data: dataToSend,
contentType: "application/json; charset=utf-8",
success: function (datar) {
window.location = '/BankCosts/Download?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
},
error: function (xhr) {
},
});
}
And this is my controller:
[HttpPost]
public ActionResult ExportToCsv(string[] ids, Search search)
{
// search is null here
}
When I spy sending data with Fiddler I can see, that I am passing this:
{"ids":[],"search":"\n {\"ID\":0,\"DateFrom\":\"2018-06-23T00:00:00\",\"DateTo\":\"2018-06-25T00:00:00\",\"hasUnrecognizedStatus\":false,\"skippedSearchResults\":0,\"paginationLimit\":100}\n"}
I think it is worth to mention, that ids is properly passed. If it contains data, that data is passed. I think the problem is that I have \ in my json. How can I remove this? Is there something wrong with my ajax?
When I use console.log to print $formData I can see that \ characters are gone and it looks better:
{"ID":0,"DateFrom":"2018-06-23T00:00:00","DateTo":"2018-06-25T00:00:00","hasUnrecognizedStatus":false,"skippedSearchResults":0,"paginationLimit":100}
[HttpPost]
public ActionResult ExportToCsv(string[] ids,[FromBody]Search search)
{
}
Try adding FromBody if your Search model is ok it should work.
based on your comments, I think that search object already stringified, so you don't need to stringify it.
just make your json like this
var dataToSend = {
"ids": allIds,
"search": $formData
};
Use JSON.parse() to transforms JSON string to a JavaScript object. Your $('#originalForm').text() is a JSON string actually.
var $formData = JSON.parse($('#originalForm').text());
var allIds = getCheckedIds();
var dataToSend = JSON.stringify({
ids: allIds,
search: $formData
});
In your case, $formData is a string (JSON string actually). So JSON.stringify() again trying to convert to JSON string which is already a JSON string that's causing unnecessary '/' character in form data that you are posting.
Make sure to set the content type to 'application/json' in ajax call properties Otherwise MVC model binder will not be able to map and fill .NET model from JSON posted data.
contentType: "application/json; charset=utf-8",
Since you are using
JSON.stringify
the search value posted in string format not object
Search
so
Try replace your controller with this
[HttpPost]
public ActionResult ExportToCsv(string[] ids, string search)
{
//then deserialize search json like
Search objSearch = JsonConvert.DeserializeObject<Search>(search);
}
or
[HttpPost]
public ActionResult ExportToCsv(string[] ids, JObject search)
{
//then deserialize search json like
Search objSearch = JsonConvert.DeserializeObject<Search >
(dataModel["search"].ToString());
}
View
$.ajax({
type: "POST",
url: '#Url.Action("ExportToCsv", "BankCosts")',
data:{ids= allIds.toString(),search:JSON.stringify($formData)}
contentType: "application/json; charset=utf-8",
success: function (datar) {
window.location = '/BankCosts/Download?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
},
error: function (xhr) {
},
});

Asp.net MVC: controller with first parameter as json and second parameter as string from View

We have a situation where we would like controller to get First parameter as json (model) as second parameter as some additional data other than model (such as Flag, source control from where event is driven etc.), we have tried tweaking with jQuery but all ended up error shown in the browser inspect element.
We have our controller typically like this:
public async Task<ActionResult> Foo(Bar b, string additionaldata)
{
if (additionaldata="Deleted")
{
}
else if (additionaldata="Favorite")
{
}
}
And inside view its something like this:
$("#delete").click(function () {
$.ajax({
url: "/Index/Foo",
type: "POST",
data: $("#myform").serialize(),
dataType: "json"
}).done(function (model) {
$("#Foo_Id").val(model.Foo.Id);
});
});
As far as model is concerned, this jQuery is working fine, but as far as we try to add some additional parameter, we are clueless.
Please suggest how we may pass it.
On option is to use FormData to build the model and add additional data
var formdata = new FormData($('#myform').get(0)); // serialize the form
formdata.append('additionaldata', 'Favorite'); // add additional properties
$.ajax({
url: '#Url.Action("Index", "Foo")',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});

MVC Send list through AJAX

Okay, I've seen tons of questions posted regarding this question, but none of the answers has actually worked for me, here's my AJAX:
$.ajax({
url: "/FilterSessions/GetFilterSession",
type: "GET",
dataType: "json",
data: jsonFilters,
traditional: true,
success: function (response) {
//Haha, it's never entering here. not really.
}
});
var "jsonFilters" contains an array with the following data:
[0] = { Path: "Test", Name: "More testing", Value: "Test Value" },
[1] = { Path: "Test", Name: "More testing", Value: "Test Value" }
And this is my controller:
public ActionResult GetFilterSession(List<FilterSessionModel> jsonFilters)
{
//Do things
return Json(false, JsonRequestBehavior.AllowGet);
}
jsonFilters always remains null... I have also tried adding contentType: "application/json; charset=utf-8" to the AJAX call... but that didn't really do anything
Finally, the class FilterSessionModel is structured as follows:
public class FilterSessionModel
{
public string Path { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
Any ideas as to what I might be missing or what might be happening?
Things I've tried so far:
Setting "traditional: true", setting "contentType", using JSON.stringify and attempting to accept a string in the MVC Controller (no-go)
UPDATE: Thanks to the answer below I realized that what was missing was to send over the data with the param Id like so:
data: "{param1ID:"+ param1Val+"}"
I would try switching out the type on your action.
List<FilterSessionModel>
Pretty sure the above is not going to work, I would try something like Object.
Or possibly a string that I would then use newton json dll to push into your List of Class.
The problem boils down to your action being unable to figure out the type, assuming you are checking your data prior to the ajax get being called.
**Update due to more info. Add in the error portion and view those vars on return from your controller, also fire up fiddler and watch what your are getting for http numbers.
$.ajax({
type: "POST",
url: "Servicename.asmx/DoSomeCalculation",
data: "{param1ID:"+ param1Val+"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
UseReturnedData(msg.d);
},
error: function(x, t, m, b) {
//Look at the vars above to see what is in them.
}
});
I think what you are looking for is answered here:
Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax
First off I'm making the assumption that your $.ajax is for JQuery and not some other Javascript framework. Please correct me if that's wrong.
ASP.NET MVC can actually do what you are asking it to (resolve data sent via AJAX to a List<FilterSessionModel>, but it seems to have a difficult time doing it via a GET request. It would help to know which version of ASP.NET MVC you are using, as more is required to get this working on the older versions. However, what I'm suggesting should work on MVC 3 or 4.
When you send AJAX via JQuery using a GET request and passing it a JavaScript array, this is what you are sending to the server:
http://localhost:50195/FilterSessions/GetFilterSession?undefined=&undefined=
It's no wonder the model is null because no data is actually being sent.
I believe ASP.NET can accept objects (and even arrays of objects) like this, but it won't do so with it formatted as JSON (like via JSON.stringify) as that just results in the following request:
http://localhost:50195/FilterSessions/GetFilterSession?[{%22Path%22:%22Test%22,%22Name%22:%22TestName%22,%22Value%22:%22Testing%22},{%22Path%22:%22Test%22,%22Name%22:%22TestName%22,%22Value%22:%22Testing%22}]
The way you probably want to do this is with a POST request. ASP.NET MVC will actually accept a JSON string as POST data and will decode it and resolve the model properly. Your AJAX code works fine with a couple modifications:
$.ajax({
url: "/FilterSessions/GetFilterSession",
type: "POST", //Changed to POST
dataType: "json",
data: JSON.stringify(jsonFilters), //Pack data in a JSON package.
contentType: "application/json; charset=utf-8", //Added so ASP recognized JSON
traditional: true,
success: function (response) {
alert('Success!');
}
});
The controller you posted should recognize POST data already, but in case it doesn't, a simple [HttpPost] attribute is all you need:
[HttpPost]
public ActionResult GetFilterSession(List<FilterSessionModel> jsonFilters)
{
//Do things
return Json(false, JsonRequestBehavior.AllowGet);
}
javascript or ajax call never type cast the object. . .you need to set type of the controller side parameter either string or List else you can also set the Object type. . If you modified codein that way.. .Your code definitely work !!!
$.ajax({
url: "/FilterSessions/GetFilterSession",
type: "GET",
dataType: "json",
data:JSON.stringify({ 'jsonFilters': jsonFilters}),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//Do your action
}
});

Passing unstructured JSON between jQuery and MVC Controller Actions

There is quite a lot of helpful information on MVC model binding.
My problem stems from the fact that I am trying to avoid creating strongly typed data in my MVC application as it mostly needs to act as a data router.
Basically, I have a set of fields on a page, with a class 'input', that I can gather with jQuery('.input'), iterate over and stuff into a javascript object. I then send this to my ASP.NET MVC controller:
var inputData = my_serialize( $('input');
$.ajax({
type:'POST',
url: '/acme/Ajax/CaptureInput',
dataType: "json",
data: { inputData: JSON.stringify(inputData) },
success: Page_Response_RegisterAndDeposit,
error: Page_AjaxError
});
On the C# side, I have
public JsonResult CaptureInput(string inputDataAsJsonString)
{
JavaScriptSerializer JSON = new JavaScriptSerializer();
object inputData = JSON.DeserializeObject(inputDataAsJsonString);
This seems like a wasteful level of indirection, I'd prefer to pass the data as contentType:application/json and have CaptureInput accept an object or IDictionary or even a dynamic.
You could use the serializeArray method. Let's suppose that you have a form containing the input elements which could be of any type and you want to invoke the following controller action:
public ActionResult CaptureInput(Dictionary<string, string> values)
{
...
}
here's how you could proceed:
<script type="text/javascript">
var values = $('form').serializeArray();
var data = {};
$.each(values, function (index, value) {
data['[' + index + '].key'] = value.name;
data['[' + index + '].value'] = value.value;
});
$.ajax({
url: '#Url.Action("CaptureInput")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (result) {
alert('success');
}
});
</script>
Not exactly what you're after but maybe the resolution of this issue would give you a partial workaround, by allowing you to bind to a simple wrapper object with an embedded Dictionary. It might even allow binding direct to a Dictionary. Not sure...
You might also need to explicitly set the json ContentType header in your $.ajax call
"JSON model binding for IDictionary<> in ASP.NET MVC/WebAPI"

Categories