Deserialize Json in mvc view - javascript

In controller I have
public JsonResult Index()
{
List<TutorialModel> models = new List<TutorialModel>();
model.TitleWord = "Go";
model.Colors = new List<bool>();
model.Colors.Add(true);
model.Colors.Add(false);
model.Colors.Add(false);
model.Colors.Add(false);
model.PossibleAnswers = new List<string>();
model.PossibleAnswers.Add("1");
model.PossibleAnswers.Add("2");
model.PossibleAnswers.Add("3");
model.PossibleAnswers.Add("4");
string ser = (new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(model);
return Json(ser, JsonRequestBehavior.AllowGet);
}
And when In view I try to catch this Json result with
<script>
var values = json.parse(#Model)
</script>
And browser shows me my serialize string. How I can deserialize this json element and store in some variable.
My model for this Controller :
public class TutorialModel
{
public string TitleWord { get; set; }
public List<string> PossibleAnswers { get; set; }
public List<bool> Colors { get; set; }
}

Note that in your Controller, you don't need to return a JsonResult - unless you're calling it as an ajax method or something. In this case, try returning an ActionResult (or ViewResult) as normal. You could do something like this:
public ActionResult Index()
{
List<TutorialModel> models = new List<TutorialModel>();
//...add items to list
return View(models);
}
Then in your cshtml javascript:
<script>
var model = #(Html.Raw(Json.Encode(Model)));
<script>

The problem is that you are returning a JsonResult so all that will be sent to the browser is your JSON, not the view you want.
You need to return a ViewResult:
public ViewResult Index()
{
List<TutorialModel> models = new List<TutorialModel>();
model.TitleWord = "Go";
model.Colors = new List<bool>();
model.Colors.Add(true);
model.Colors.Add(false);
model.Colors.Add(false);
model.Colors.Add(false);
model.PossibleAnswers = new List<string>();
model.PossibleAnswers.Add("1");
model.PossibleAnswers.Add("2");
model.PossibleAnswers.Add("3");
model.PossibleAnswers.Add("4");
string ser = (new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(model);
return View("Index", ser);
}
Then in your view you can have:
<script>
var values = JSON.parse("#Model")
</script>

Related

Error posting record to db asp.net mvc

I am building a scheduling system using fullcalendar for MVC, my get event retrieves from a view for a specific location.
However, my post / save event inserts into the table that the view is made from, containing all locations.
I am getting an error when I try to add the new event to the data connection.
"The field Location must be a string or array type with a maximum length of '1'." string
PropertyName "Location" string
I tried to set the string for the event manually before adding it to the data connection but this isn't working for some reason. Could it be me not declaring the string correctly?
//Actions for Calendar 5
public JsonResult GetEvents5()
{
using (CalgaryNEEntities dc = new CalgaryNEEntities())
{
var events = dc.CalgaryNEEvents.ToList();
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
[HttpPost]
public JsonResult SaveEvent5(EventsAllLocation e)
{
var status = false;
using (InsertEntities dc = new InsertEntities())
{
if (e.EventID > 0)
{
//Update the event
var v = dc.EventsAllLocations.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
var locationstring = "Calgary NE Kitchens";
v.CompanyName = e.CompanyName;
v.Start = e.Start;
v.End = e.End;
v.KitchenNumber = e.KitchenNumber;
v.Location = locationstring;
}
}
else
{
var locationstring = "Calgary NE Kitchens";
e.Location = locationstring;
dc.EventsAllLocations.Add(e);
}
dc.SaveChanges();
status = true;
}
return new JsonResult { Data = new { status = status } };
}
Here is the EventsAllLocation definition:
public partial class EventsAllLocation
{
public int EventID { get; set; }
public string Location { get; set; }
public string CompanyName { get; set; }
public System.DateTime Start { get; set; }
public Nullable<System.DateTime> End { get; set; }
public string KitchenNumber { get; set; }
}
Any tips or help would be greatly appreciated, thanks!
The answer is staring you in the face !! LOL
"The field Location must be a string or array type with a maximum
length of '1'." string PropertyName "Location" string

dropdownlist not showing data properly

i have this dropdown list which get the data from db but does not display the data properly n the view
The codes are as follows:
View:
#Html.DropDownListFor(m=> Model.SystemRAteModel.Role, new SelectList(Model.SystemRAteModel.GetRole.Items),"Value","Text")
Model:
public class SystemRolesModel
{
public static RoleProvider Provider { get; internal set; }
public int ID { get; set; }
public String Role { get; set; }
public Boolean Status { get; set; }
public SelectList GetRole { get; set; }
}
Controller
public ActionResult Index()
{
IApplicationLogic app = new ApplicationLogic(session);
RateManagementModel RTM = new RateManagementModel();
var value = app.GetVatValue();
var freight = app.GetFreightValue();
// var systemrolemodel = new SystemRolesModel();
//var currency = new List<SelectList>();
// currency= app.GetListOfRoles();
//IList<string> ERModel = new List<string>();
//foreach (var _currency in currency)
//{
// var curent = _currency.ToString();
// ERModel.Add(curent);
//}
var sysmodel = new SystemRolesModel();
sysmodel.GetRole = getRoleSelectList();
RTM.SystemRAteModel = sysmodel;
ViewData["ViewVatValue"] = value;
//ViewData["ViewCurrency"] = new SelectList(currency);
//ViewBag.LocationList = freight;
ViewData["ViewFreightValue"] = freight;
return View("Index",RTM);
}
public SelectList getRoleSelectList()
{
IApplicationLogic app = new ApplicationLogic(session);
var roles = app.GetListOfRoles();
SystemRoles sr = new SystemRoles();
sr.Id = -1;
sr.Role = "--select role--";
roles.Add(sr);
IEnumerable<SystemRoles> sortedRoles = roles.OrderBy(d => d.Id);
IList<SystemRoles> _sortedRoles = sortedRoles.ToList();
return new SelectList(_sortedRoles, "Id", "Role");
}
i have tried everything on the net but cant get a hand on it. Please any help will do.OutPut of my System At the moment
You don't need to create a new SelectList again in View, as you are already creating that in controller side and passing it via Model, you should be able to directly use it in View like:
#Html.DropDownListFor(m=> Model.SystemRAteModel.Role,Model.SystemRAteModel.GetRole)
This should populate the dropdown with the values, but it would display same values for all the items for now, as your code is setting hard-coded same values for all properties here:
SystemRoles sr = new SystemRoles();
sr.Id = -1;
sr.Role = "--select role--";
roles.Add(sr);
You would need to change it to have proper values.
Another easy way can be to use the constructor of SelectList this way:
public SelectList getRoleSelectList()
{
IApplicationLogic app = new ApplicationLogic(session);
var roles = app.GetListOfRoles().OrderBy(x=> x.RoleID);
return new SelectList(roles.ToList(), "RoleID", "Role");
}
you will just need to replace RoldID and Role property name with the proerty names you have in the DTO.
Hope it helps.
See this example:
#Html.DropDownList("Name", Model.Select(modelItem => new SelectListItem
{
Text = modelItem.Name,
Value = modelItem.Id.ToString(),
Selected = modelItem.Id == "12314124"
}))

How to pass a variable (besides a set of records) from a controller to a razor view

I have an api controller and a viewmodel as given below that fetch a set of records from an sql db and pass it to a razor view into a kendo grid.
Viewmodel:
public class SoonDueReportsViewModel
{
public SoonDueReportsViewModel()
{
}
public string ARAName { get; set; }
public int? ReportAraId { get; set; }
public string CompanyName { get; set; }
public int? CompanyId { get; set; }
public string ReportDetails { get; set; }
public DateTime? DueReportDate { get; set; }
public int ReportId { get; set; }
}
Controller:
public class AllDueReportsController : BaseApiController
{
private readonly IIdentityStorage identityStorage;
public IQueryable<SoonDueReportsViewModel> Get()
{
AppKatPrincipal appKatPrincipal = identityStorage.GetPrincipal();
var araIds = UnitOfWork.GetAll<UserGroup>()
.Where(group => group.Id == appKatPrincipal.GroupId)
.SelectMany(group => group.ARA).Select(ara => ara.Id);
var duties = UnitOfWork.GetAll<Duty>();
var companies = UnitOfWork.GetAll<Company>();
var aras = UnitOfWork.GetAll<ARA>().Where(x => araIds.Contains(x.Id));
var userGroupId = indireKatPrincipal.GroupId;
var userGroup = UnitOfWork.GetById<UserGroup>(userGroupId);
var foreRun = userGroup.ForRun.GetValueOrDefault();
var nextDate = DateTime.Today.AddMonths(foreRun); // The value of this variable I need to transport also to the view !!
var query = from ara in aras
join company in companies on ara.Id equals company.ARA
join duty in duties on company.Id equals duty.CompanyId
where duty.ReportedDate == null
&& company.Activ == true
select new SoonDueReportsViewModel
{
ARAName = ara.Name,
ReportAraId = ara.Id,
CompanyName = company.Name,
CompanyId = company.ID,
ReportDetails = duty.Details,
DueReportDate = duty.ReportDate,
ReportId = duty.Id,
};
return query;
}
}
Everything works fine, but in addition to the set of records (defined by the query) I also need to transport the value of the variable 'nextDate' to the same view.
If someone could give me a hint how to do this, I'd appreciate it a lot.
Regards, Manu

$http undefined error when fetching data from asp.net controller

I am using angularjs in asp.net
I made a controller with CRUD and am trying to get data from angularjs controller using $http service
Route params is getting correct querys from url, i tested that, but i get undefined error when requesting data
What am i doing wrong? :(
SongsController.cs method:
public ActionResult Index(string id)
{
/*var result = db.Songs.ToList();
return Json(result, JsonRequestBehavior.AllowGet);*/
string searchString = id;
var songs = from m in db.Songs
select m;
if (!String.IsNullOrEmpty(searchString))
{
songs = songs.Where(s => s.Title.Contains(searchString));
}
return Json(songs, JsonRequestBehavior.AllowGet);
}
songsService.js:
myApp.factory('songsService', ['$http', function ($http) {
var songsService = {};
songsService.getSongs = function (param) {
return $http.get('/Songs/Index/' + param);
}
return songsService;}])
songsController.js:
myApp.controller('songsController', ['$scope', '$routeParams', 'songsService', function ($scope, $routeParams, songsService) {
var search = $routeParams.query;
if (search == 'undefined' || search == null)
search = '';
getSongs(search);
function getSongs(searchText) {
songsService.getSongs(searchText)
.success(function (data) {
$scope.songs = data;
})
.error(function (error) {
$scope.status = 'Unable to load data: ' + error.message;
console.log($scope.status);
});
}}]);
EDIT:
Song class:
using System;
using System.Collections.Generic;
public class Song
{
public int ID { get; set; }
public string Title { get; set; }
public string Artist { get; set; }
public virtual ICollection<Navigation> Navigations { get; set; }
}
EDIT2: Navigation class:
using System;
public class Navigation
{
public int ID { get; set; }
public int SongID { get; set; }
public int PlaylistID { get; set; }
public virtual Song Song { get; set; }
public virtual Playlist Playlist { get; set; }
}
EDIT3:
If I name my .cs controller SongsController and navigate to url songs/index/something i get popup if i want to open or save something.json and just get redirected back to my default url defined by ngroute (#/songs/)
But, if i name .cs controller something else, like RandomController, if i navigate to same url i get this error:
A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.Navigation_7A1A3B789B740F23BAB0A6DAABE519BE3A‌​F91C300893047C23FF2FD8C44E6705'.
EDIT4: I've come to point at which everything if my SongsController.cs looks like this:
public ActionResult Index(string id)
{
var song = new List<Song>
{
new Song{Title="Paint It Black",Artist="Rolling Stones"},
new Song{Title="People Are Strange",Artist="The Doors"},
new Song{Title="With Or Without You",Artist="U2"},
new Song{Title="Wish You Were Here",Artist="Pink Floyd"},
new Song{Title="Fluorescent Adolescent",Artist="Arctic Monkeys"},
new Song{Title="La Guitarra",Artist="Orjan Nilsen"},
new Song{Title="Ping Pong",Artist="Armin Van Buuren"},
new Song{Title="Fade Out Lines",Artist="The Avenger"},
new Song{Title="Redemption Song",Artist="Bob Marley"},
new Song{Title="Wherever I May Roam",Artist="Metallica"},
};
return Json(songs, JsonRequestBehavior.AllowGet);*/
}
If it' like that everything works, but if it looks like i've wrote in original post i get undefined error when i run $http.get :/
EDIT5: Okay, I believe the problem is i'm trying to send objects containing array of Navigation class objects, how can i solve this? :(
You have a circular reference on your Song class.
When the Json serializer tries to process it, it finds the Navigations property and tries to serialize that as well, the problem is that each Navigation object on that collection have a instance of the same Song, so it enters a infinite loop trying to serialize all of it over and over again.
That happens because EntityFramework has its lazyloading and automatically populate the classes as the serializer tries to access them.
To fix it, you can do two things, simply disable the lazyloading for that call in particular:
public ActionResult Index(string id)
{
db.Configuration.LazyLoadingEnabled = false;
string searchString = id;
var songs = from m in db.Songs
select m;
if (!String.IsNullOrEmpty(searchString))
{
songs = songs.Where(s => s.Title.Contains(searchString));
}
return Json(songs, JsonRequestBehavior.AllowGet);
}
The other option is to create a model with only the data you need to return and populate it manually (or using a mapper tool).
public ActionResult Index(string id)
{
db.Configuration.LazyLoadingEnabled = false;
string searchString = id;
var songs = from m in db.Songs
select m;
if (!String.IsNullOrEmpty(searchString))
{
songs = songs.Where(s => s.Title.Contains(searchString));
}
var mappedSongs = songs.Select(it => new { Title = it.Title, Artist = it.Artist }).ToList();
return Json(mappedSongs , JsonRequestBehavior.AllowGet);
}

Controller do not receive values passed from json.stringify(obj)

I am not understand this case:
I have a model like:
public class ExmDescobertos {
public int Id { get; set; }
public int ExameId { get; set; }
public int PlanoId { get; set; }
public int ConvenioId { get; set; }
}
And create an object javascript:
var objDescoberto = new Object();
objDescoberto.Id = $("#hdnDescobertoId").val(); //inputs with values...
objDescoberto.ExameId = $('#hdnExameId').val();
objDescoberto.PlanoId = $('#hdnPlanoId').val();
objDescoberto.ConvenioId = $('#hdnConvenioId').val();
And I am using Json.stringify(obj) to transmit the values with a $.post jQuery method:
var dados = JSON.stringify(objDescoberto);
In this point, dados is "{"Id":"27","ExameId":"53","PlanoId":"32","ConvenioId":"11"}", for example.
And have a controller with this action:
public PartialViewResult(ExmDescobertos descoberto) { }
But... the parameter in this controller not receive your values correct! :o
In this point descoberto is Id = 0; ExameId = 0; PlanoId = 0; ConvenioId = 0;
Not errors explicit, but not works...
Anybody have a idea of what I have missing?
Thank you for all!
Don't stringify you object, just send object as is.
$.post("/url", objDescoberto);
or
var dados = JSON.stringify({descoberto : objDescoberto});

Categories

Resources