using viewbag data with jquery json - javascript

I want to use my ViewBag in JavaScript array. I follow using viewbag with jquery asp.net mvc 3, and I think the following code is what I am looking for,
#model MyViewModel
<script type="text/javascript">
var model = #Html.Raw(Json.Encode(Model));
// at this stage model is a javascript variable containing
// your server side view model so you could manipulate it as you wish
if(model.IsLocal)
{
alert("hello " + model.FirstName);
}
</script>
But this code causes error for Json.Encode, then I add System.Runtime.Serialization.Json, but It also cause error for Encode, says no method for Encode, I already include Newtonsoft.Json, but still no result.
My ViewBag data ::
public ActionResult Dashboard()
{
ViewBag.inc = (from inc in db.Incident select inc.Title).ToList();
return View();
}
And I want to use this ViewBag.inc data in JavaScript array

As you said, you are already referencing the Newtonsoft Json.Net library, you can use this following code::
var inc = '#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.inc))';
inc= JSON.parse(inc);
$.each(inc, function(index, data) {
//you next code
});

The snippet you are using does not use the ViewBag, but the Model. Regardless, if you want to print the serialisation of an object to the view, and you are already referencing the Newtonsoft Json.Net library (as you said you are), then you can do the following:
var model = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
If you want to use the item in the ViewBag instead, you can do:
var model = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.inc));

You can use like for ViewBag -
var mn = #{#Html.Raw(Json.Encode(ViewBag.ViewBagProperty));}
alert(mn.YourModelProperty);
And for Model -
var mn = #{#Html.Raw(Json.Encode(Model));}
alert(mn.YourModelProperty);
There is no need for NewtonSoft.Json, we can use default System.Web.Helpers.Json.
Update: Here goes the complete solution with Model, the same concept can be used with ViewBag too -
Lets say you have this Model -
public class XhrViewModel
{
public string data1 { get; set; }
public string data2 { get; set; }
}
Then in the controller action you are constructing the List of above Model in following way -
public ActionResult GetData()
{
List<XhrViewModel> model = new List<XhrViewModel>();
model.Add(new XhrViewModel() { data1 = "Rami", data2 = "Ramilu" });
return View(model);
}
Then on the View, you can have something like this -
#model IEnumerable<Rami.Vemula.Dev.Mvc.Controllers.XhrViewModel>
#{
ViewBag.Title = "GetData";
}
<h2>GetData</h2>
<script type="text/javascript">
var mn = #{#Html.Raw(Json.Encode(Model));}
alert(mn[0].data1);
</script>
And when you execute the page -

Related

How to pass list from controller to javascript function in asp.net mvc?

I have this query in the controller:
DataClasses1DataContext behzad = new DataClasses1DataContext();
var query = (from p in behzad.ImagePaths
select new
{
p.name
}).ToList();
ViewBag.movies = query;
return View();
and write this java script code in view page:
function behi() {
#{
var behzad = ViewBag.movies;
}
alert('#(behzad)');
}
that java script code show me this:
how can i write java script code for show controller query result?thanks all.
Serialize it. The below code use Newtonsoft's Json serializer to do so.
var movies = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.movies));
Now the movies variable will be an array of items, each with a name property.
Serialize return object to json like below, and use it in the javascript.
JavaScriptSerializer class is in System.Web.Script.Serialization package.
Hope this helps.
DataClasses1DataContext behzad = new DataClasses1DataContext();
var query = (from p in behzad.ImagePaths
select new
{
p.name
}).ToList();
ViewBag.movies = new JavaScriptSerializer().Serialize(query);
return View();

Model is null when I'm trying to use it in JavaScript

My app arhitecture is ASP.Net MVC
I'm trying to pass some data from the mssql server using entity framework ORM.
This is the code from my action.
public ActionResult Create()
{
List<object> myModel = new List<object>();
var places = db.Places.Where(p => p.UserId == User.Identity.GetUserId());
myModel.Add(places);
myModel.Add(new Place());
ViewBag.UserId = new SelectList(db.AspNetUsers, "Id", "UserName");
return View(myModel);
}
The code from my view
#model IEnumerable<object>
#{
List<WhereWeDoIt.Models.Place> places = Model.ToList()[0] as List<WhereWeDoIt.Models.Place>;
WhereWeDoIt.Models.Place place = Model.ToList()[1] as WhereWeDoIt.Models.Place;
ViewBag.Title = "Create";
}
...
<script type="text/javascript">
//Users data
var json = #Html.Raw(Json.Encode(places));
console.log("Places test " + json);
</script>
...
The console will output "null"
What am I doing wrong?
Once Html.Raw will get the string and put it directly in the html, try
to put the #Html.Raw between single quotes like:
var json = '#Html.Raw(Json.Encode(places))';
Regards,
The solution that I've provided above will set the json to json string (not object) so will not work, sorry about that. Below there is the solution (simulated and tested in my machine)
Well, we have some things going on here.
I have accomplished success in the code doing so:
#model IEnumerable<object>
#{
var places = Model.ToList()[0];
HypothesisWebMVC.Models.Place place = Model.ToList()[1] as HypothesisWebMVC.Models.Place;
ViewBag.Title = "Create";
}
<script type="text/javascript">
//Users data
var json = #Html.Raw(Json.Encode(places));
console.log("Places test " + json);
</script>
This code will set the json variable to a an object (the places list set in the controller).
I don't know what are your goal but that code that I´ve posted above will work.
Some considerations:
In the actions, when you do:
List<object> myModel = new List<object>();
var places = db.Places.Where(p => p.UserId == User.Identity.GetUserId());
myModel.Add(places);
myModel.Add(new Place());
You're creating an myModel that will have in the first position and list (or IQueryable) of Place, and in the second position a single place (not a list), so you can not convert the whole model to a list.
You could use:
List<WhereWeDoIt.Models.Place> places = Model.ToList()[0] as List<WhereWeDoIt.Models.Place>;
By, when adding to the model, do a .ToList() before inserting.
Consider using a view model (an object created specific for the view)
Hope I've helped.
Regards,
I test your code. Edit view like this:
List<WhereWeDoIt.Models.Place> places = Model.ToList() as List<WhereWeDoIt.Models.Place>;
Model.ToList()[0] is not list.

asp.net mvc, returning multiple views as JSON

Is it possible to return 2 separate views to an ajax call in Asp.net?
for example, if foo1 and foo2 are 2 ActionResult methods each returning a view?
return Json(new { a = foo1(), b = foo2() });
currently attempting this, the end result is that javascript gets it back as a class object rather then the actual view, anybody know how to get the resulting rendered html instead?
EDIT: I guess what I'm actually going for, is there a way for me to return the rendered view in string format?
Yes their is a way of returning view in string format.
For this you need to do following things:
1.You need some method in which you can pass your viewname along with object model. For this please refer below code and add to your helper class.
public static class RenderViewLib
{
public static string RenderPartialView(this Controller controller, string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
}
The above code will return your view in string format.
2.Now call above method from your json call like this:
[HttpPost]
public JsonResult GetData()
{
Mymodel model = new Mymodel();
JsonResult jr = null;
jr = Json(new
{
ViewHtml = this.RenderPartialView("_ViewName", model),
ViewHtml2 = this.RenderPartialView("_ViewName2", model),
IsSuccess = true
}, JsonRequestBehavior.AllowGet);
return jr;
}
and you will get your view as string format from your json call.
Hope this is what you are looking for.

How to get Data from Model to JavaScript MVC 4?

that's my function:
<script> function Calculate()
{
var ItemPrice = document.getElementById("price");
var weight = document.getElementById("weight");
var SelWeight = weight.options[weight.selectedIndex].value;
alert(SelWeight);
var Category = document.getElementById("SelectedCategory");
var SelCategory = Category.options[Category.selectedIndex].value;
alert(SelCategory);
}
</script>
i want to get SelCategories.Tax and SelCategories.Duty to add them to weight value and total price to show the total in a label.. I'm using ASP.NET MVC 4 and this is my Model that i want to use
public class CategoriesModel
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public decimal Duty { get; set; }
public decimal Tax { get; set; }
public IEnumerable<SelectListItem> CategoriesList { get; set; }
}
I think the best approach here is to use Json and something like Vue.js, Knockout.js, etc. (but also you can do it without these libraries, if your case is simple).
First, you need to install Json support with a command in PM console:
PM> install-package NewtonSoft.Json
Then, in your view you can convert your model to javascript object like this:
#model ...
#using Newtonsoft.Json
...
<script type="text/javascript">
var data = #Html.Raw(JsonConvert.SerializeObject(this.Model));
</script>
Then you can access all the properties in your model with in plain JavaScript:
var id = data.CategoryID;
That's it! Use knockout (update 2018: this is obsolete, there is no reason you should use knockout now) if your logic is complicated and you want to make your view more powerful. It could be a little bit confusing for newbie, but when you get it, you'll gain the super-powerful knowledge and will be able to simplify your view code significantly.
You need to create actions (methods in the controller) that return JsonResult.
From the client side, make ajax calls to the server to recover and use that data. The easiest way to do this is to use any of the jQuery ajax methods.
public JsonResult GetData(int id)
{
// This returned data is a sample. You should get it using some logic
// This can be an object or an anonymous object like this:
var returnedData = new
{
id,
age = 23,
name = "John Smith"
};
return Json(returnedData, JsonRequestBehavior.AllowGet);
}
When you use a jQuery get to the /ControllerName/GetData/id, you'll get a JavaScript object in the success callback that can be used in the browser. This JavaScript object will have exactly the same properties that you defined in the server side.
For example:
function getAjaxData(id) {
var data = { id: id };
$.get('/Extras/GetData/1', // url
data, // parameters for action
function (response) { // success callback
// response has the same properties as the server returnedObject
alert(JSON.stringify(response));
},
'json' // dataType
);
}
Of course, in the success callback, instead of making an alert, just use the response object, for example
if (response.age < 18) { ... };
Note that the age property defined in the server can be used in the JavaScript response.
If you prefer a class try jsmodel. After converting the mvc view model to javascript it adds the benefit of retrieving DOM updates.
var jsmodel = new JSModel(#Html.Raw(Json.Encode(Model)));
Then anytime you want to get the latest state of the DOM do this to update your variable:
var model = jsmodel.refresh();
Website:
http://chadkuehn.com/jquery-viewmodel-object-with-current-values/
There is also a nuget:
https://www.nuget.org/packages/jsmodel/
var errors = '#Html.Raw(Json.Encode(ViewData.ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage)))';
var errorMessage=JSON.parse(errors);

Present JSON data to a play framework template

Trying to get it to work without any detail knowledge of JQuery. I am really having a hard time finding an comprehensible example of how i would create an unnumbered list out of some json that i am passing to the front inside a String object.
I am using the Play! Framework. My Application has a method that returns a string holding an json array of items.
GET /items controllers.Application.items()
the method looks like this:
public static Result items() {
return ok(Json.toJson(Item.all()));
}
How would you process this data in order to have your template present it as an unnumbered list?
the data, example:
#Entity
public class Item {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public int id;
public String title;
public String type;
public int quantity;
public BigDecimal unitPrice;
public Item() {}
public static List<Item> all() {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("defaultPersistenceUnit");
EntityManager entityManager = entityManagerFactory.createEntityManager();
TypedQuery<Item> query = entityManager.createQuery("SELECT i FROM Item i", Item.class);
return query.getResultList();
}
You need to call the items() action with a javascript ajax request. Then you can use javascript and jQuery to create your list.
something like this:
<script type="text/javascript">
$(function(){
$.getJSON('/items', function(items){
var ul = $('<ul>');
$.each(items, function(item){
var li = $('<li>').text(item.title);
ul.append(li);
});
$('body').append(ul);
});
});
</script>

Categories

Resources