Convert razor model to json and use to angular - c#

I'm trying to use AngularJs to MVC5, but my problem is I don't have any Idea how to get the data from razor #model using AngularJs.
So I decide to convert the #Model to json but it's not working.
_Layout.cshtml
Razor #model
#model IEnumerable<GoActive.Models.ActiveDirectory2>
AngularJs
<script>
(function () {
var app = angular.module('app', []);
var response = #Model.AsRawJson(); // But .AsRawJson(); is not allowed in this one.
})();
</script>

Alternatively you could convert the entire server-side model into a JS object using Json.Encode
var model = #Html.Raw(Json.Encode(Model));
In case if you Model is a collection then you can use a sequential for loop to iterate over your model collection. So the complete code would be something like..
<script type="text/javascript">
var model = #Html.Raw(Json.Encode(Model));
for (var i = 0; i < model.length; i++) {
alert(model[i].myValue);
// Do Something with your model
}
</script>

try this once.
<div data-ng-init="angularModel=#razorModel"></div>

Related

Return json to partial view in core 2

I would like to create a view that would contain a different view. I've never used json before. How i can do this and How can I format the json data in the view?
My first function "Details" is to retrieve a object from the database and return view "Details.cshtml". In this view I want generates a partial view ("Stats.cshtml"). And now I want to generate a partial view with the data downloaded in the json format inside the Stats function.
Controller
public IActionResult Details(int? id = 1)
{
var person = _context.Persons.Find(id);
return View(champion);
}
public IActionResult Stats()
{
var json = new WebClient().DownloadString("url");
return Json(s);
}
View - Details.cshtml
#model Person
<div class=row">
<div class="col-sm-5"> #Model.Name </div>
<div class="col-sm-5"> #Html.Partial("Stats") </div>
</div>
View - Stats.cshtml
<h2>Stats</h2>
<div> here I want to put in a json field </div>
When I run "Stats" function from the address localhost/Home/Stats I get the result in json, but when I run "Details" function I get view "Details" and "Stats" without the json value.
to render a partial, you have many options, by your code,
the simplest one is: move your Stats code to Details action
public ActionResult Details()
{
...//prepare your person viewModel
var result = new WebClient().DownloadString("url");
var stats = JsonConvert.DeserializeObject<YourViewModel>(result);
//you have 2 options to return data
yourPersonModel.Stats=stats ; //<== you have to change PersonViewModel
//or ViewBag.Stats=stats;
return View(yourPersonModel);
}
then in Details.cshtml:
#Html.Partial("Stats", ViewBag.Stats or Model.Stats)//by your choice before.
Since Html.Action is removed, but ViewComponent comes in Core, you cannot directly call it right now, but this link will tell you how to make it back: #Html.Action in Asp.Net Core
public ActionResult Stats()
{
var result = new WebClient().DownloadString("url");
var yourViewModel = JsonConvert.DeserializeObject<YourViewModel>(result);
return PartialView(yourViewModel);
}
add the following code in your View - Stats.cshtml:
#model YourViewModel
then in Details.cshtml:
#Html.Action("Stats")
Be aware that Html.Action cannot call async actions, be careful to use it.
the next solution is to use new feature ViewComponent, here is details:
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-2.1
the last one will not be what you expected: use AJAX to load this partial page on page Details is loaded to client

How to retrieve data from view bag in jquery(inside the view) in c#, mvc

I'm sending a List using ViewBag to the view like this.
List<RegionSearch> rs = searchregionArray.Select(sr => new RegionSearch()
{
region = (string)sr["AREA/DEST"],
}).ToList();
var filteredRegion = rs.Select(k => k.region).Distinct();
//testing
ViewBag.checking = rs;
now I want to get it in <script></script> .how can I do that
Try this :-
<script>
var jsonList = '#Html.Raw(Json.Convert(ViewBag.checking))'
var jsList = JSON.parse(jsonList);
console.log(jsList);
</script>
NOTE :- Although not a good idea sending whole list from controller to view inside ViewBag instead use ViewModel.

MVC4 - AutoComplete using Json

I'm working on an intranet web app using ASP.NET MVC4 and Entity Framework. On one of my views, I have a list of persons which might be huge in the future. So, to make things easier, I wanted to implement an autocomplete field component using jQuery UI and Json.
The thing is that when I'm using my database to provide a source to my jQuery code, it is not working. However, when I create a variable by hard coding data, it works.
My Action :
public ActionResult AutoComplete(string term)
{
BuSIMaterial.Models.BuSIMaterialEntities db = new Models.BuSIMaterialEntities();
//var result = new [] {"A","B","C","D","E","F"}; with this, it works
var result = (from obj in db.Persons where obj.FirstName.ToLower().Contains(term.ToLower()) select obj).ToArray(); // with this, it doesn't work
return Json(result, JsonRequestBehavior.AllowGet);
}
My View :
#{
ViewBag.Title = "Auto";
}
<h2>Auto</h2>
<label for="persons">Persons : </label><input type="text" id="persons" name="persons"/>
#section Scripts
{
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
#Styles.Render("~/Content/themes/base/css")
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('#persons').autocomplete({
source: '#Url.Action("AutoComplete")'
});
});
</script>
}
I tried to modify my return type (JsonResult instead of ActionResult) but nothing changes. Any idea to solve this problem?
The reason your code doesn't work is because you are attempting to send a domain model to the view which most probably contains circular references in its object graph and is not JSON serializable. To fix the problem do this:
public ActionResult AutoComplete(string term)
{
BuSIMaterial.Models.BuSIMaterialEntities db = new Models.BuSIMaterialEntities();
//var result = new [] {"A","B","C","D","E","F"}; with this, it works
var result = db
.Persons
.Where(p => p.FirstName.ToLower().Contains(term.ToLower()))
.Select(p => p.FirstName) // <!-- That's the important bit you were missing
.ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
Notice how I am projecting the Person entity to a string (taking only its FirstName). In your example you were directly taking the entire Person object which doesn't make sense for the autocomplete plugin as you need to send an array of strings to the view.

How can i use model in Javascript?

Example :
<script type="text/javascript">
function abc() {
var t = document.getElementById("name").value;
#foreach(Player pl in Model){
if (t == pl.Name) {
alert("This name is already use!");
}
}
</script>
Error : t - cannot resolve symbol
How can i use JavaScript variable in C# code? Is it possible in this example?
You cannot use JS variables in C# code , but you can use C# variables in the code.
In most cases C# is used to render HTML or JS.
In your case it would be best if you render your C# serverside model as a JS array , which you can later on iterate.
make an action that returns your list (assuming it's a list) as
a JSON
fetch the data with an AJAX get call to your action.
Cheers!
You may do something like this.
<script type="text/javascript">
function abc(players) {
var t = document.getElementById("name").value;
for(p in players) {
if (t == p.Name) {
alert("This name is already use!");
}
}
abc(#Html.Raw(Json.Encode( Model )));
</script>

How to pass an object from a mvc controller action to a view using jquery

Can someone help me out I'm new to jQuery, I would like to know how can I pass an object through from a controller action MVC
public ActionResult UserGroupSetting()
{
UserGroupSetting setting = //some code to retrieve the settings
ViewData["Theme"] = setting.Theme;
ViewData["Image"] = setting.LogoImage;
returnView(setting);
}
What I want its to get the Theme and the logo image, in a jQuery function, that I will use to update a class in a stylesheet, The theme object contains a colour in Hex form only for now.
If someone can please help me with the call to a jquery function and how will I expose both the image and the theme objects in jquery.. Thanks
You can return the data in jSon format and let jquery make a call to your action method with getJSON method
public ActionResult UserGroupSetting()
{
var result=new { Theme="YourTheme", Logo="YourLogoURL"};
return Json(result, JsonRequestBehavior.AllowGet);
}
In your page,Call this from your javascript
$(function(){
$.getJSON('YourController/UserGroupSetting', function(data) {
alert(data.Theme);
alert(data.Logo);
});
});
if i were you , i would do this:
you can use ViewBag: in action: ViewBag.Setting = setting;
UserGroupSetting setting = //some code to retrieve the settings
ViewBag.Theme = setting.Theme;
ViewData.Image = setting.LogoImage;
returnView(setting);
then in Razor:
#{
var setting = (UserGroupSetting)ViewBag.Setting;
}
output it to javascript tag:
<script type="text/javascript">
var setting = new setting{
Theme = #setting.Theme,
Image = #setting.Image
}
</script>
This may not be the best solution, but one option I've used in the past is to create a hidden input in your view and access the value of the input in your jQuery code. This would be an example of the code you would have in your view:
<input id="someID" type="hidden" value="#TempData["Theme"]" />

Categories

Resources