I am working on my AutoComplete widget, using Angular JS - Material, in C# ASP.NET MVC.
In this example, I'm trying to get an AutoComplete of States to work. I started with this tutorial, but need to have the options come from the database (at this point, just static list of options in the controller).
Here is a link to my current code (relevant files).
When I run the code, I can see that the list of objects from the controller are pulling through properly - an array of 4 objects, each with an Id and a Name (as shown in my controller method). However, the options are not being loaded into the input form.
When I click into the textbox, I get an "option" that says No states matching "" were found. If I type in 'a', I get the "option" that says No states matching "a" were found. This is what I would expect to happen if there actually were no matching results.
My question: How do I change my code to load the options with what I'm pulling from the controller?
Thanks in advance!
Here's a screen shot of the results:
Here's the key JavaScript/AngularJS code:
//TODO: Replace data.json with /Home/GetStates
$http.get('data.json')
.then(function(response) {
self.states = response.data.map(function(state) {
return {
value: state.Name.toLowerCase(),
display: state.Name
};
});
});
You'll need to replace 'data.json' with '/Home/GetStates' for it to call your backend MVC JSON RESTful API Service. Note that I also left the functions querySearch(query) and createFilterFor(query) in place and changed self.states=loadStates() to self.states=null since the $http.get() service will now load the states.
I did test your C# MVC controller code and everything looks good with it.
Here's a working Plunker, http://plnkr.co/edit/tDC6KcO1O8VSGwVghBo7?p=preview.
Hope this helps. Let me know if you need anything else.
Here's what I did to fix the problem:
Changed to POST
Set variable = result, then returned the results
Here's the code:
function querySearch(query) {
if (query == undefined) {
console.log("invalid");
return;
}
$http({
method: 'POST',
url: self.URL_Get + query,
searchTerm: query
}).then(function(response) {
self.states = response.data;
});
return self.states;
}
Related
I want to list all the projects that were returned from my API call with React. I currently only have the C# code that gets all the projects that the user has authorization for and displays it in JSON format. Hardcoded the personalaccesstoken in the code (because I don't know how else to do it tbh). Now, I wish to list all the projects returned with React so that the user can select the desired project they want to work on from a dropdown menu.
I have little experience with React and have never used it with REST API's.
( If someone has the answer to the question above, I would greatly appreciate the help with another problem. I'm also trying to create a new repository in the project that the user has selected, and I want them to be able to specify the name of this repository with an input field. Once the user has specified the desired repository name and chosen the project from the dropdown menu, they should be able to hit "Submit" in order to start a POST Request to the REST API and create the new repository in the project. This will also be done with React. )
You may need check this code repos: azure-devops-node-api-sample. We have done provide the sample code in that repo.
Get project:
public async getProjects(
stateFilter?: any,
top?: number,
skip?: number,
continuationToken?: string,
getDefaultTeamImageUrl?: boolean
): Promise<CoreInterfaces.TeamProjectReference[]> {
return new Promise<CoreInterfaces.TeamProjectReference[]>(async (resolve, reject) => {
let routeValues: any = {
};
let queryValues: any = {
stateFilter: stateFilter,
'$top': top,
'$skip': skip,
continuationToken: continuationToken,
getDefaultTeamImageUrl: getDefaultTeamImageUrl,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.0-preview.4",
"core",
"603fe2ac-9723-48b9-88ad-09305aa6c6e1",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<CoreInterfaces.TeamProjectReference[]>;
res = await this.rest.get<CoreInterfaces.TeamProjectReference[]>(url, options);
let ret = this.formatResponse(res.result,
CoreInterfaces.TypeInfo.TeamProjectReference,
true);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
You can continue to check this sample page, it shows you many samples including create project.
It makes me in trouble when I write jQuery Ajax calls for each task in my whole application. I write jQuery Ajax calls to update the interface after a specific event, such as updating a dropdown list when another dropdown list selection changes.
I need the fastest way to handle Ajax requests across my application and to avoid code repetition.
// code sample to ajax request which I used
function onChange(bookid) {
$.ajax({
type: "GET",
url: '#Url.Action("books","subject")',
data : { bookid: bookid},
dataType: "json",
success: function (result) {
alert('success');
//do whatever you want
},
error: function(result){
}
});
};
If you are looking for an approach that would simplify these kind of ajax call to update interface after specific events, using asp.net mvc 4, I would suggest that you look into the awesome awesome set of helpers.
Be assured that it's a very easy to learn set of helpers.
I encourage to go to the Live demo and play with it for a while. You will rapidly realize its great potential.
Then an example with master - slave dropdown list (first element on the default demo page).
Here is the code that goes into the view:
Cascading using binding to Parent:<br />
<%:Html.Awe().AjaxDropdown("Category")
.Url(Url.Action("GetCategories","Home")) %>
<%:Html.Awe().AjaxDropdown("ChildMeal")
.Url(Url.Action("GetMeals","Home"))
.Parent("Category") %>
The first dropdown is an ÀjaxDropDownnamedCategory. It is filled by executing an action method calledGetCategoriesfound on a controller calledHomeController` (in this example these are meals categories).
Note that Awesome uses some conventions in certains cases. For example if we had limited the first AjaxDropDown declaration to <%:Html.Awe().AjaxDropdown("Category")%>then the Awesome will assume that we would fill the dropdown from an action method called GetItems and it would expect to find it on a controller called CategoryAjaxDropDownController. But since we have specified the url with the corresponding action, it would look for the specified action method on a controller called SPECIFIED_NAME+Controller (in this example HomeController)
The second's name is ChildMeal, it's parent is the Category ajax drop down and it is filled when the selected element is changed in the Category drop down, and when that happens it is filled by executing the GetMeals action method from the HomeController controller.
Here is the code for the action methods in the HomeController
public ActionResult GetCategories(int? v)
{
var items = Db.Categories
.Select(o => new SelectableItem(o.Id, o.Name, v == o.Id));// value, text, selected
return Json(items);
}
public ActionResult GetMeals(int? v, int? parent)
{
var items = Db.Meals.Where(o => o.Category.Id == parent)
.Select(o => new SelectableItem(o.Id, o.Name, v == o.Id));// key, text, selected
return Json(items);
}
As you can see from the return object the JSON handling complexity is managed by Awesome and it all becomes transparent to the developer (you just have to invoke Json(items) to have it done.
The Db object provides the datas. You may use a class that inherits from System.Data.Entity.DbContextin order to load datas from a database.
You have many other similar components (such as the AjaxRadioList, the AjaxCheckBoxList, the AjaxList, the AutoComplete component, ...) among many very interesting rich components.
I suggest that you go to the live demo, play with it, see the various examples and the source codes, then you try to create your first awesome project.
well jQUery's ajax call's about as fast as your going to get - there is not a lot of overhead on the client side at all .
as far as extra code .. for each call:
function onChange(bookid) {
$.ajax({
type: "GET", // not needed - default GET
url: '#Url.Action("books","subject")',
data : { bookid: bookid},
dataType: "json", // not needed - jQuery will guess
success: function (result) {
alert('success');
//do whatever you want
},
error: function(result){ // not needed if you're leaving empty
}
});
};
could be
$.get('#Url.Action("books" , "subject")' , { bookid: bookid}, function(result){
alert(result);
});
I have developed an application in MVC5. Onclick of a link on the View below code gets invoked -
// Code in View File
$.post('../ControllerName/FunctionName', //this is your url
{
id: image,
}, function (data) {
alert("Successfully published");
}
).error(function () {
alert("Failed to publish");
});
//Code in Controller
[HttpPost]
public void ISPPDF(string id)
{}
Issue that i am facing is the ISPPDF() function gets invoked when i run it through visual studio.However after i hosted my application on server it does not seem to call the function..
I feel there is some issue with the path i have specified -
i also tried specifying path the below ways but no luck!
/ControllerName/FunctionName
ControllerName/FunctionName
Any help would be appreciated.
Thanks,
You should never hard-code URLs in MVC.
Instead use #Url.Action.
$.post('#Url.Action("FunctionName", "ControllerName")', //this is your url
If you need to send parameters, you do it like this:
$.post('#Url.Action("FunctionName", "ControllerName", new { id = Model.ID })', //this is your url
And there are two important reasons why I recommend this:
1. The chances of mistyping the URL are huge. This Questions proves it, the OP mistyped the URL.
2. Url.Action takes into account your route. If your route changes, Url.Action will know how to build the correct URL. This way you will not have to go through multiple views to change all the hard-coded values.
Try this as your post method is in view file
$.post('../FunctionName',{ id: image,}, function (data) { alert("Successfully published");}).error(function () {alert("Failed to publish"); });
I have been struggling on trying to work this for the last 3 days, how do you pass data from an api controller into an mvc controller and use the data to populate a selectlistitem.
I have seen plenty of examples of calling the api from the webpage which is all well and good, but what if the user has javascript disabled, it will not display the data.
So any help with an example for this would be much appreciated.
My code is:
web.api
public IEnumerable<DisplayCurrencyInDDL> GetCurrencyForDDL()
{
var s = _ICurr.InsetCurrencyIntoDataBase();
return s.AsEnumerable();
}
mvc controller
WebClient wc = new WebClient();
var s = wc.DownloadString("http://localhost:50687/api/Currency");
How do I get the value from var s (currency and currencyid) into a selectlistitem.
Thanks
George
edit data returned as: [ { "strCountry": "Afghan Afghani", "strCountryCode": "AFN" }, { "strCountry": "Albanian Lek", "strCountryCode": "ALL" }, { "strCountry": "Algerian Dinar", "strCountryCode": "DZD" }, { "strCountry": "Andorra Euro1",
I don't understand why you are doing it this way.
If you want to share some code you can do this by moving the code into
some Library and instantiate that class in WebAPI and also in your MVC
Controller.
Ok, so after reading this post on stackoverflow difference between apiController and controller
Its my understanding that if i'm returning data to my own website, then use mvc controller, but if i'm allowing a 3rd party to consume data from my site, then put the data in an api controller.
Also if a user visited my site/your site and had javascript disabled, then json would not work on the client side as requires jQuery etc, so my understanding is use api if you are sure the visitor will not have javascript disabled.
Please let me know if that correct
I am kinda new in web development, looking for secured way to update SQL Database from the client side, or in other description updating the database without refreshing the webpage like (like facebook button).
I searched a lot and found that it can be done by using a web service and call it by javascript or using javascript direct or ajax, but which is the best and secured way and there is any other way to do it ?
thanks..
you can use ajax for updating database from client side.. Like if you click a button in web page, get the click event of that page through JavaScript or jQuery then through ajax you can perform database update. See the code below:
For catching event(like my button id is button1):
$('#<%=button1.ClientID%>').click(function{
$.ajax({
type: "POST",
url: "default.aspx/UpdateDatabase",
data: "{'textboxvalue':'" + $('<%=textbox1.ClientID%>').val() + "'}'
contentType: "application/json;charset=utf-8",
datatype: "json",
success: UpdateDone
});
});
In above code you have passed one value from a textbox1 to function UpdateDatabse in Default.aspx page(Please defined this function as [WebMethod]). then do your update in this function and return some string or bool value so that you can judge that update is done then value in success is name of function that will run if your function runs successfully so define that function in JavaScript or jQuery like
function UpdateDone(response)
{
if(response.d == 'done')
{ alert('Update is done'); }
else
{ alert('Sorry Update not done'); }
}
Above code will not do any postback you see that your value is updated in database. Please note that the function you make in C# page please mark it as WebMethod and it will be a static method, then only your JavaScript can find that function.
Hope this will resolve your problem.
The term ajax you use is correct but already a bit old. The new kids on the block are called SPA's where SPA stands for Single Page Application
It does what you want to achieve to the extreme: no more page refreshes. So it seems a good way to start
Here is The ASP.NET Single Page Application homepage
My advice is to research and invest time in one of the (many) javascript frameworks that will help you achieve this goal much faster. Hand coding javascript and make it work cross browser is too much work. The ASP.NET team choose upshot.js to solve your problem and it seems a fine choice.
Screenshot take from here
I found doing AJAX with JSON with ASP.NET MVC 3 to be easiest method of doing AJAX requests. Then you can have a specific action method that handles the request and makes the updates the database via Entity Framework(EF).
Essentially only passing the data that needs to be updated in the JSON. From there the MVC Action receives the JSON, and uses EF to lookup the DB record, apply/save changes. It can even respond with a success message which your AJAX can use to update some field that verifies the data was saved for the user(you could even do something where you have a "Saving..." message appear between the first ajax request and the response.)
This will allow you to send the request without refreshing your page. All your DB access code will be server side in the Action method.
This example shows how you might do a json request. You would modify this by adding additional code to the Create method to interact with entity framework(or your database tool of choice) to update a record based on the Person person parameter that was passed in(notice MVC did a really nice thing of converting the json data into a nice Person class!)
http://juristr.com/blog/2011/08/posting-json-data-to-aspnet-mvc-3-web/
If the data the user will enter in the webform is sensitive, you would need to encrypt it before sending the json request. I would personally just setup the website to use SSL. Anything you cook up on your own probably won't be as secure as SSL.
The code you add to the Create method might look like this:
//Find the person that they are attempting to edit
Person currentPerson = db.Persons.Find(person.PersonKey);
//update the database fields based on the submitted data(I would probably actually use AutoMapper for this
currentPerson.Name = person.Name;
currentPerson.DateOfBith = person.DateOfBirth;
//etc.
db.SaveChanges();
//compose a JSON response object indicating success, you would want to combine this with a try catch in the above to reply regarding failures as well