How to Get Model Object to Javascript variable - javascript

i have an action like below in my controller and the object of one Viewmodel class i had send as an argumnet to view. The problem is i need to get this object values in
javascript.
public ActionResult FillChecklist()
{
classOne objVM=new classone();
objVM.List=//get list
objVM.Id=//someid
objVM.List2=//secondlist
return View(objVM);
}
i had tried something like below but it does not works. i know hidden variable assign is a solution but i don't know if model class has many lists then how can i get the list in javascript.
<script type="text/javascript>
var obj=#Model;
</script>
i had tried the below method too. but it shows the name json is not exist in this current context
var obj = JSON.parse('#Html.Raw(Json.Encode(Model))');
please help me to solve this issue.

I just ran a test for you with the following code:
#model Project.ViewModels.TestViewModel
#using System.Web.Helpers
<script type="text/javascript">
var obj = JSON.parse('#Html.Raw(Json.Encode(Model))');
</script>
ViewModel:
public class TestViewModel
{
public string Test { get; set; }
}
It produces the following output:
<script type="text/javascript">
var obj = JSON.parse('{"Test":"Value123"}');
</script>

Related

Changing current viewModel in .NET MVC application

My View uses the Model like below:
public class ObjectViewModel
{
public int ChosenVariant{ get; set; }
public List<Object> Objects{ get; set; }
}
but on page I am displaying details only of one of Object from the list (whose id is equal ChosenVariant).
On the same page I have radio buttons and each of them is binded to one of the Objects from the list:
#foreach (var obj in Model.Objects)
{
<div class="radio">
#{
var options = new RouteValueDictionary();
options["onchange"] = "UpdatePage()";
if (product.ID == Model.ChosenVariant)
{
options["checked"] = "checked";
}
}
#Html.RadioButtonFor(p => Model.ChosenVariant, #product.ID, options)
</div>
}
My problem is that how I can refresh the Model.ChosenVariant and render once again page without refresh?
My first idea was returning whole Model with new value of Model.ChosenVariant in javascript function (on onchange radio button).
This function will call Post action to a Controler, which return once again whole Model (but with new changed Model.ChosenVariant. Then on done action of this Post call I will use $(panel).html(data); for refresh the page.
Is there any easier way to change the current viewmodel without calling Controller?

How to assign value in $(document).ready from code behind

i'm developing a .net application using twitter bootstrap.
I'm trying to get data from .aspx.cs page to .aspx page.
Please find my code below:
strOblect.cs
public class strObject
{
public string Name { get; set; }
public string Description { get; set; }
}
.aspx.cs page:
public List<strObject> stringList = new List<strObject>();
protected void Page_Load(object sender, EventArgs e)
{
strObject ObjOne=new strObject();
ObjOne.Name="One";
ObjOne.Description ="One";
stringList.Add(ObjOne);
strObject ObjTwo=new strObject();
ObjTwo.Name="Two";
ObjTwo.Description ="Two";
stringList.Add(ObjTwo);
strObject ObjThree=new strObject();
ObjThree.Name="Three";
ObjThree.Description ="Three";
stringList.Add(ObjThree);
}
.aspx:
<asp:Panel ID="pnlData" runat="server" style="background-color:White;">
<script type="text/javascript">
$(document).ready(function () {
var valueAssigned=stringList;
});
</script>
</asp:Panel>
I'm unable to get stringList value in $(document).ready.
Please help me out to get the value.
It appears that your stringList is actually a collection of objects. In order to use it in JavaScript as such, you'll need to serialize it to a javascript object.
var valueAssigned=<%=new JavaScriptSerializer().Serialize(stringList)%>;
So that you can wind up with the following:
var valueAssigned= [{Name: "Foo", Description: "Bar"}, {...}];
Edit
JavaScriptSerializer is in System.Web.Script.Serialization - you'll either need to add this below at the top of your <%# Page
<%# Import Namespace="System.Web.Script.Serialization" %>
or specify the FQ name
var valueAssigned=<%=new System.Web.Script.Serialization.JavaScriptSerializer()
.Serialize(stringList)%>;
StuartLC's answer will be enough.JSON is very good option for that purpose. Other option can be to register client script in aspx.cs. Here is another SO question regarding that
How do I pass data from c# to jquery/javascript?

How can I obtain an array list from DOM into javascript?

I don't know how obtain an Objects arrayList that is coming from the Spring Controller.
This is my Controller which is returning an Array List of objects.
Controller
#RequestMapping(value = "hello", method = RequestMethod.GET)
public ModelAndView showMessage(Principal p,HttpServletResponse response) {
ModelAndView mv = new ModelAndView("mapa");
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
mv.addObject("postossaude", Lists.newArrayList(PostosSaude.findAll()));
return mv;
}
This is the Postosaude.java Object wchich has all the info I need to rescue.
#Entity
public class Postosaude {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String nome_posto_saude;
private double latitude;
private double longitude;
private String endereco;
public Postosaude()
{}
//gets and sets...
}
`
This is my mapa.html which is receiving the List ( I use Thymeleaf to obtain the list).
mapa.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
var NodeListPostosSaude = document.getElementsByName('postossaude'); // ?? I want to obtain the "postossaude" list
alert(NodeListPostosSaude.length);
</script>
</head>
<body>
<p th:text="${#vars.get('postossaude')}"> </p> //I check that the list is arriving OK (it prints the three objects that are in my list:
//"[palmaslab.mapas.repository.Postosaude#e7228c7a, palmaslab.mapas.repository.Postosaude#478808dc, palmaslab.mapas.repository.Postosaude#f35bea7d]"
</body>
</html>
So, I want to obtain this List into my script but i dont know how to do it. Do you know any javascript method or jQuery method to obtain that?
My objective is, using this array Objects list (inside of it are different object with geo cordinates) to make a googlemaps customized like that
As per the discussion in the comments, here's my solution - JSBin
HTML
<div id="container">
<!-- P tags generated -->
<p>Data Value 1</p>
<p>Data Value 2</p>
<p>Data Value 3</p>
<p>Data Value 4</p>
</div>
JS
var container = document.getElementById('container');
var p = container.getElementsByTagName('p');
var array = [];
for (i = 0; i < p.length; i++) {
array.push(p[i].innerHTML)
}
console.log(array)

Grid.Mvc.Ajax extension grid initialization

Hi I'm very new to Web GUI dev using JQuery & Ajax and I'm trying to get the nuget package Grid.MVC.Ajax working. The readme states the following:
Follow thse steps to use Grid.Mvc.Ajax
1. Include ~/Scripts/gridmvc-ext.js after your ~/Scripts/grimvc.js include.
2. Include ~/Content/ladda-bootstrap/ladda-themeless.min.css CSS after your Bootstrap CSS/LESS include.
3. Include Ladda-bootstrap Javascript via the ~/Scripts/ladda-bootstrap/ladda.min.js
and ~/Scripts/ladda-bootstrap/spin.min.js.
4. Create a view model for you grid data, for example:
public Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
5. Add a Razor partial view for your grid data that uses an AjaxGrid<T> as the model type,
Where T is your view model type:
#using GridMvc.Html
#using GridMvc.Sorting
#model Grid.Mvc.Ajax.GridExtensions.AjaxGrid<Models.Person>
#Html.Grid(Model).Columns(columns =>
{
columns.Add(c => c.FirstName);
columns.Add(c => c.LastName);
}).Sortable(true).WithPaging(10)
6. Add a controller action to retrieve the data for the first page of data that includes the Ajax pager HTML:
public JsonResult Persons()
{
var vm = new List<Person>()
{
new Person() { FirstName = "John", LastName = "Doe" }
}
.AsQueryable();
var ajaxGridFactory = new Grid.Mvc.Ajax.GridExtensions.AjaxGridFactory();
var grid = ajaxGridFactory.CreateAjaxGrid(vm, 1, false);
}
7. Add a controller action to retrieve data for paged items that returns a JsonResult without the Ajax page HTML:
public JsonResult PersonsPaged(int page)
{
var vm = new List<Person>()
{
new Person() { FirstName = "John", LastName = "Doe" }
}
.AsQueryable();
var ajaxGridFactory = new Grid.Mvc.Ajax.GridExtensions.AjaxGridFactory();
var grid = ajaxGridFactory.CreateAjaxGrid(vm, page, true);
}
8. Call the ajaxify Grid.Mvc.Ajax JavaScript plug-in method setting the non-paged and paged controller actions and optionally a form
to apply additional filtering to the grid. All input and select elements in the given form will be passed into your paged and non-paged controller actions:
$(".grid-mvc").gridmvc().ajaxify({
getPagedData: '/Home/Persons',
getData : '/Home/PersonsPaged',
gridFilterForm: $("#gridFilters")
});
I have set things up as stated but I'm having problems in step 8. as I'm not sure how to call the JavaScript code in order to populate the grid. I have enclosed the above in a $(document).ready call but that doesn't seem to work :-( Any help would be much appreciated. Thanks
You have two options: loadPage and refreshFullPage
this will call your PersonsPaged method:
$(".grid-mvc")
.gridmvc()
.loadPage()
and this will call your Persons method.
$(".grid-mvc")
.gridmvc()
.refreshFullGrid()
also, in your Persons and PersonsPaged you can return a JSON like this:
public ActionResult Persons()
{
var vm = new List<Person>()
{
new Person() { FirstName = "John", LastName = "Doe" }
}.AsQueryable();
var ajaxGridFactory = new AjaxGridFactory();
var grid = ajaxGridFactory.CreateAjaxGrid(vm, 1, false);
return Json(new { Html = grid.ToJson("_YourPartialWithGridCode", this), grid.HasItems },JsonRequestBehavior.AllowGet);
}
I resolved the problem adding the URI.js file on the scripts tag before gridmvc.js and gridmvc-ext.js. When I installed Grid.Mvc.Ajax by Nuget, it added this file.
I called the code inside the $(document).ready(function() { ... }) and used twice ways.
1 - The javascript object of the grid using the grid's name.
2 - I did the same way that you did calling ajaxify method after gridmvc method using a jquery selector and it worked to me.
<script>
$(document).ready(function () {
$(".grid-mvc").gridmvc().ajaxify(
{
getPagedData: "/Product/Grid",
getData: "/Product/Index"
});
});
</script>
or
<script>
$(document).ready(function () {
pageGrids.productGrid.ajaxify(
{
getPagedData: "/Product/Grid",
getData: "/Product/Index"
});
});
</script>
"productGrid" is the grid's name. I hope to have helped.

Asp.net mvc passing a C# object to Javascript

I have c# class say options more like AjaxOptions.
public class options
{
public string Url {get;set;}
public string httpMethod {get;set}
}
and a javascript function like this
function dosomething(obj)
{
if (obj.Url!="" and obj.HttpMethod=="something")
loadsomething();
}
Now in my Controller action
public class mycontroller : controller
{
public ActionResult WhatToDo()
{
options obj = new options{Url="someurl"};
return PartialView(obj);
}
}
in my view I need this object kind of string which i should be able to pass to my method.
#model options
<script>
dosomething(#model.SomeFunctionToConverToString())
</script>
So I need this SomeFunctionToConverToString method which i will convert this object to string.
Thanks
You should be able to use it like you would any other output of a model property in your view. Just reference the property that you want to pass in the JS function.
#model options
<script>
dosomething('#(model.Url)');
</script>
See this post for more information on using Razor inside of JS
EDIT - Something that might catch you is that if your URL get's broken from the HTML encoding that Razor does using the above, you can use the #Html.Raw() function which will pass the Url property without HTML encoding it.
<script>
dosomething('#Html.Raw(model.Url)');
</script>
EDIT 2 - And another SO post to the rescue! You are going to most likely want to convert your model to JSON in order to use in a Javascript function. So...in order to do that - you will need something in your view model to handle a JSON object.
public class optionsViewModel
{
public options Options{get;set;}
public string JsonData{get;set;}
}
and in your controller:
public class mycontroller : controller
{
public ActionResult WhatToDo()
{
options obj = new options{Url="someurl"};
var myViewModel = new optionsViewModel;
myViewModel.options = obj;
var serializer = new JavaScriptSerializer();
myViewModel.JsonData = serializer.Serialize(data);
return PartialView(myViewModel);
}
}
And finally the view:
#model optionsViewModel
<script>
dosomething('#model.JsonData')
</script>
Using this method, then your function will work as expected:
function dosomething(obj)
{
if (obj.Url!="" and obj.HttpMethod=="something")
loadsomething();
}
EDIT 3 Potentially the simplest way yet? Same premise as edit 2, however this is using the View to JsonEncode the model. There are probably some good arguments on either side whether this should be done in the view, controller, or repository/service layer. However, for doing the conversion in the view...
#model options
<script>
dosomething('#Html.Raw(Json.Encode(Model))');
</script>
Try this:
<script type="text/javascript">
var obj= #Html.Raw(Json.Encode(Model));
function dosomething(obj){}
</script>
That's work for me
Client side:
function GoWild(jsonData)
{
alert(jsonData);
}
Alert print :
{"wildDetails":{"Name":"Al","Id":1}}
MVC Razor Side:
#{var serializer new System.Web.Script.Serialization.JavaScriptSerializer();}
<div onclick="GoWild('#serializer.Serialize(Model.wildDetails)')"> Serialize It </div>
there is also a syntax error
<script type="text/javascript">
dosomething("#Model.Stringify()");
</script>
note the quotes around #Model.Stringify() are for javascript, so the emitted HTML will be:
<script type="text/javascript">
dosomething("this model has been stringified!");
</script>
I would recommend you have a look at SignalR, it allows for server triggered javascript callbacks.
See Scott H site for details: http://www.hanselman.com/blog/AsynchronousScalableWebApplicationsWithRealtimePersistentLongrunningConnectionsWithSignalR.aspx
In summary thou ...
Javascript Client:
var chat = $.connection.chat;
chat.name = prompt("What's your name?", "");
chat.receive = function(name, message){
$("#messages").append("
"+name+": "+message);
}
$("#send-button").click(function(){
chat.distribute($("#text-input").val());
});
Server:
public class Chat : Hub {
public void Distribute(string message) {
Clients.receive(Caller.name, message);
}
}
So .. Clients.receive in C# ends up triggering the chat.receive function in javascript.
It's also available via NuGet.

Categories