Typeahead in ASP.net MVC - javascript

The first image shows that the method I created in user class.
The second image shows the controller that I created. How I take the data from GetGroupManagerAndFranchiseConsultantList? What should I need to write within view?

Right now you are returning Json. So I assume you are calling this call from something like this
<script>
$.getJSON("/Search",function(data){
// data is a JS OBJECT of your JSON data.
});
</script>
If you were looking to use MVC Views you need to return it as a view and use the built-in model binding.

Related

Render Partial View from Javascript and pass model

I need to create partial views dynamically which require a model that is initially used. I can serialize the model and pass it to a javascript function but I can't figure out how to pass using jquery api load.
Here's what I'm currently doing.
var loader = $('<div class="loader"></div>');
loader.load(url);
$(cl).append(loader);
I call the partial like this in the cshtml page. This works fine.
#Html.RenderPartial("~/Views/Shared/_PartialView.cshtml", Model);
Also, calling load like this works works as well.
load('#Url.Action("_PartialViewAction", "Home")')
The issue is, I need to pass the model with it from a javascript/jquery call.
Update
So this was my mistake. It must be a Friday morning thing - this is actually very simple to accomplish. I only need to pass the serialized data to the controller and it loads the partial view.
You can save the object into a javascript var:
<script>
var viewModel = #Html.Raw(JsonNetConverter.Serialize(Model))
</script>
or like this :
var viewModel = { VariationID: #Model.id, ProductID: #Model.product, InStock: #Model.isStock, Price: #Model.price };
And leter take it:
load('#Url.Action("_PartialViewAction", "Home")', viewModel)

AngularJS - generating view from .NET controller only executed once

I have a MVC .NET application with AngularJS. In my route provider I use the controllers of mvc for retreiving the views as follows:
.when('/Units', {
templateUrl: 'Unit/Units'
})
.when('/UnitsDetail', {
templateUrl: 'Unit/UnitsDetail'
})
And my .NET UnitController has the following methods:
[Authorize]
public ActionResult Units()
{
return View();
}
[Authorize]
public ActionResult UnitsDetail()
{
ViewBag.reference = Guid.NewGuid().ToString().Substring(0, 6);
return View();
}
For the UnitsDetail view I need a reference that is generated in the UnitsDetail() method.
The problem comes when I go from Units to UnitsDetail several times. The first time the UnitsDetail() method is called and thus, the reference is generated but if I go back to Units and access again UnitsDetail the method is not called and the reference is the same. I need to generate one reference each time.
I know I could generate it using JS in the client or make an AJAX request from Angular to the server but what I really want to know is how to make Angular call the method UnitsDetail() every time I go to "#/UnitsDetail".
Thanks!
By default angular will cache all views in its template cache.
This is by design.
Angular expects the view to be just static HTML with the dynamic part marked using the {{ dynamicScopeVariable }} code. Angular will use scope objects to replaces the dynamic bit . But the static part will be shown from the cache.
The first time you execute the view , the view is cached.
You have 2 options here. Actually just one which is good from the Design point of you #2.
Option #1
Disable template caching in Angular as shown here
https://stackoverflow.com/a/27432167/2794980
This means that angular will call the HTML ACTION every time it needs the view.
This is not the best way to use angualar but it will work. You should also consider the performance side .. By far the most time consuming call on a ASP.NET MVC applications are Actions calls. This method means that while you are using a client side MVC framework , you are not utilizing one of its important benifits.
Options #2
Use a angualar service to get the GUID from back end . i.e. the code below.
ViewBag.reference = Guid.NewGuid().ToString().Substring(0, 6);
Preferably use a WebAPI if u can ( your request will be small ). The use angular to replace the GUID in ur VIEW.
It is not clear from the question why you need the GUID and if you could do with generating a random unique number using Javascript . If that is possible , it might be the best solution . But based on the info in the question you could use either of option 1 or 2.
Edit : Didn't realize that you have already tried option 2 , in that case Option 1 it is.
Edit 2 : If you want to remove a single element from the cache , you can do
$templateCache.remove("<Element Name>");
or you could use the
$cacheFactory.remove("Name")
Read more about cache factory here :
https://docs.angularjs.org/api/ng/service/$cacheFactory
The name is generally the page name , you can look at the template cache or cache factory object in debugger console to find the exact name.

AngularJS Filter Data Binding

I have a custom filter that I use to return an html string using $sce.trustAsHtml. In the template/view I use ng-bind-html directive and pass the filter to as follows:
<div ng-bind-html="userAgent | geoCode:business"></div>
Inside my filter I have an inner function that takes an input, business model in my case, which takes properties from the business model, a mongoosejs model, and generates a formatted string which is used to generate and html a tag:
'<a href="some_url_i_create" ...>'+ myFormattingInnerFunction(business) +'</a>';
What is strange is, if I use this function several of the fields are returned as undefined/blank. However, if I directly access the variables a follows:
'<a href="some_url_i_create" ...>'+ business.prop1 + business.prop2+ ... +'</a>';
Then all of the properties are found and output. Any ideas?
P.S. The model is a retrieved via an AJAX request, which in turn use mongoosejs to retrieve the data, inside of the angular controller for this section.
When you are calling the function you are accessing the business object on the first rendering event when all the scripts are loaded and the first DOM manipulation occurs.
But When you accessing the business object directly angular puts the values into the view on the first rendering event and on all of the digest events and of course on other rendering events.
You might want to consider using a $scope. attr in the template to render and call the formated string value method in the callback as well.
In the JS:
.success(function(data){
business=JSON.parse(data);//Iguess
$scope.formatedtext= myFormattingInnerFunction(business);
$scope.$apply();// If you use an angular libs callback this probably not needed.
})
In the template:
'<a href="some_url_i_create" ...>'+ formatedtext +'</a>';

Knockout JS Templates makes the UI "flash" when edited

I have a big problem with using Knockout JS. In my view model I have a field, called Method, that is actually an other view model.
This view model can be one of three different things (it is mapped to a polymorphic object in the domain model). To solve this I use templates that checks which type of Method that is selected withing the domain model and then shows the template that binds data for that type.
The function that checks the type of method looks like:
this.getTemplate = function (data) {
var method = data.original.get_Method();
if (method instanceof MyProj.MethodA)
return "methodA";
else if (method instanceof MyProj.MethodB)
return "methodB";
else if (method instanceof MyProj.MethodC)
return "methodC";
}
The markup where I bind the template looks like:
<div data-bind="template: {name: getTemplate($data), data: $data.Method}"></div>
This actually works very nice and when I change the type of method via an dropdown in the UI the domain model updates and the right template is shown. However here comes my problem. Each template contains a number of different fields that are specific for each method type. Whenever I change one of the values in the view model displayed by one of the templates the UI flashes and I think that happens because the template get selected again. This is quite irritating and looks extremly bad.
Any ideas on how to solve this problem? Any help would be greatly appreciated!
Thanks in advance
/Björn
Did you use any observable inside the getTemplate function. Updating the value of that observable makes the template rerender and you get your flash effect.
Checkout this link Part : "Note 5: Dynamically choosing which template is used".

JSON object from ASP.NET controller to view

I have a situation where a when a web page is accessed a controller action runs which retrieves the data for that page based on a user selection. I am attempting to send the data back to the page as a JSON object, however, the data opens up as one large string in an HTML page. The controller action, in a nutshell, looks like the following snippet:
Public JsonResult MyMethod(string userSelection)
{
string userData = (string) Data;
return Json(userData, “text”, JsonRequestBehavior.AllowGet);
}
I first tried to use the JQuery $.getJson() method but I think this is wrong as I believe it issues another call to the action method for the data, which is not what I want to do. What I want is to access the JSON object in JavaScript code so I can use the property data to populate fields on the web page. The basic question is what must I do in my JavaScript to receive the JSON object when the page is first rendered? I apologize if I am missing something fundamental; this is my first try.
I still had no luck today but when I left work I came up with a strategy walking to my car. A user makes a selection from a page that presents a list prior to entering the page on which I cannot figure out how to work with JsonResult. Part of the problem is the user selection contains a link that calls the controller/action that returns the JsonResult which conflicts with using $.getJson() within the page where I want to work with JsonResult. So here is my strategy: When the user makes the selection that brings them to the (problematic) page, I will call a controller/action that strictly works with (ASP) ViewData, and use the ViewData to initially present that page. Once on the page, the user can change the selection -- I will handle this with a JavaScript event that uses a $.getJason() call to a different controller/action method that works with (ASP) JsonResult. After I try this strategy I shall post my results for whomever is interested.
You want parseJSON not getJSON
http://api.jquery.com/jQuery.parseJSON/
Edit - Oh wait you are pointing your browser at the JsonResult as if it was an ActionResult? That is not going to work.
Render a proper view, and use getJSON to call the JsonResult action.
getJSON is what you are looking for. Call that on the DOM ready event which will executes once the DOM finishes loading.
$(function(){
//This code will be executed on the DOM ready ( when the page is loaded)
$.getJSON("YourControllerName/MyMethod?userSelection=someValue",function(data){
alert(data.FirstName);
alert(data.AnotherPropertyName);
});
});
getJSON is a shorthand of jQuery ajax method with datatype set as json
Assuming your JSON data you are retuning is something like this
{
"FirstName": "Scott",
"AnotherPropertyName": "SomeValue"
}
To return data like above, change your Action method like this
public JsonResult MyMethod(string userSelection)
{
var result=new { FirstName="Scott", AnotherPropertyName="Great"};
return Json(result,JsonRequestBehavior.AllowGet);
}

Categories