Model is null when I'm trying to use it in JavaScript - 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.

Related

Not Showing the output of Json Data from controller to the view

I am trying to to show the Json data from controller to the view. It works fine in my test project, but when I copied the work in the main project it gives error.
It says Url does not exist in the current context. Although it works fine in the test project and doesn't give this error.
Controller Code -
public JsonResult GetFreight()
{
string url = "https://digitalapi.auspost.com.au/postage/parcel/domestic/calculate.json?length=22&to_postcode=3000&from_postcode=2000&weight=1.5&height=7.7&width=16&service_code=AUS_PARCEL_REGULAR";
//synchronous client.
var client = new WebClient();
client.Headers.Add("auth-key:a1234567-abcd-abcd-1234-1234567890abc");
var content = client.DownloadString(url);
var serializer = new JavaScriptSerializer();
var jsonContent = serializer.Deserialize<Object>(content);
return Json(jsonContent, JsonRequestBehavior.AllowGet);
}
View Code
<script>
var weather = Object();
$(document).ready(function () {
$.get("#Url.Action("GetFreight", "ShoppingCart")", function (response) {
//response
console.log(response);
weather = ko.mapping.fromJS(response); //populate the weather object
ko.applyBindings(weather);
});
});
</script>
<td>Freight = <span data-bind="text:postage_result.total_cost"></span></td>
I want to mention one more thing- In the main project the view is placed in another subfolder called "ShoppingCart" so do I need to change anything in the script when calling the method from the controller? Any help will be appreciated.
Thanks.

asp.net Javascript window.location Url.Action not working

I try to get a JavaScript working within ASP.NET
My JavaScript:
function reportOrder(sender, args) {
alert("Message");
window.location.href = #Url.Action("StartReport", "PrintOut", New With {.Area = "Printing", Key .ReportName = "Test",
Key .typeOfReport = TypeOfPrintingIS.Order,
Key .CompanyId = DirectCast(ViewData("CompanyId"), Guid),
Key .ExchangePrintData = CType(locOrderReport, ExchangeData.IExchangePrintData)});
}
First of all, the function works, when I disable the window.location, the alert is raised! So, the Problem has to be within the #UrlAction(
And also, the Area is working, because, when I use a similar Html.RenderAction function with an other directive to another function, it works fine.
The function within the Controller:
<HttpPost>
Function StartReport(ReportName As String, typeOfReport As TypeOfPrintingIS, CompanyId As Guid, ExchangePrintData As Code.ExchangeData.IExchangePrintData) As ActionResult
Dim model As New HTML5ViewerModel()
model.ViewerOptions.UseUIMiniStyle = True
locReportHelper.CompanyId = CompanyId
locReportHelper.ReportName = ReportName
locReportHelper.TypeOfReport = typeOfReport
locReportHelper.ExchangePrintData = ExchangePrintData
model.ReportName = locReportHelper.CreateReportId
Return View("Html5Viewer", model)
End Function
And the "IExchangePrintData" Interface is an empty Interface to verify the correct class.
Does anyone of you got an idea?
THX a lot - Have a nice weekend
Try to wrap your razor directive with single quotation marks. It looks like this one: window.location.href = '#Url.Action("SomeActionName", "SomeControllerName", etc...)';
Guess this should work, cause of you mentioned #Html.RenderAction worked fine.

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();

Flot.js & JQuery.Ajax: Create graph from key-value-pair

I'm trying to create a graph in mvc using flot.js. The graph will be a line graph with 3 lines on it. I have created a set of 3 list keyvaluepair with date/value to be plotted on the graph as shown in the code below. Currently i get : JavaScript runtime error: 'listvoltage' is undefined
Here's what I tried already:
Index.cshtml:
#if (Model != null)
{
foreach (var item in Model.BatteryInfo)
{
var listvoltage = new List<KeyValuePair<double, int>>();
var listtemperature = new List<KeyValuePair<double, int>>();
var listlevel = new List<KeyValuePair<double, int>>();
listvoltage.Add(new KeyValuePair<double, int>(
TMTMonitorAndCompare_Helpers.DateTimeHelpers.DateTimeToUnixTimestamp(item.TEST_DATE), Convert.ToInt32(item.battery_voltage)));
listtemperature.Add(new KeyValuePair<double, int>(
TMTMonitorAndCompare_Helpers.DateTimeHelpers.DateTimeToUnixTimestamp(item.TEST_DATE), Convert.ToInt32(item.battery_temperature)));
listlevel.Add(new KeyValuePair<double, int>(
TMTMonitorAndCompare_Helpers.DateTimeHelpers.DateTimeToUnixTimestamp(item.TEST_DATE), Convert.ToInt32(item.battery_level)));
CustomGraphinScript.js
$(document).ready(function () {
$.plot($("#placeholder"), listvoltage, { yaxis: { max: 1000 } });
});
Could anyone tell me what I need to do to the above to display this data on graph? is ajax required?
Razor file is executing on the server side. flot.js is executing on client/browser and they dont share the same type system. Thats why 'listvoltage' is undefined.
Put this in your razorfile. Lookout for Date conversion between .NET and Javascript. flot.js need Javascript timestamp.
#using System.Web.Script.Serialization
<script>
#{
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(listvoltage);
}
var timeserie = #Html.Raw(json);
</script>
Consider a Web API solution with JSON result and Ajax call.

using viewbag data with jquery json

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 -

Categories

Resources