Jquery/ajax get object from a class and use it in a textbox in my view
asp.net-mvc-3, c#, jquery
Solution
Javascript or jQuery for that matter doesn't know what a `method` means. jQuery doesn't know what C# is. jQuery doesn't know what ASP.NET MVC is. jQuery doesn't know what the `Person` .NET class means. jQuery doesn't know what a .NET class means.
jQuery is a javascript framework which (among many other things) could be used to send AJAX requests to a server side script.
In ASP.NET MVC those server side scripts are called controller actions. In Java those are called servlets. In PHP - PHP scripts. And so on...
So you could write a controller action that could be queried using AJAX and which will return a JSON serialized instance of the `Person` class:
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
and then:
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
This obviously assumes that your Person class has `FirstName` and `LastName` properties:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Problem
I am working on a asp.net mv3 application. In a helper class I have a method that return an object of a person based on his ID ``` public Person GetPersonByID(string id) { // I get the person from a list with the given ID and return it } ``` In a view I need to create a jquery or javascript function that can call the `GetPersonByID` ``` function getPerson(id) { //I need to get the person object by calling the GetPersonByID from the C# //helper class and put the values Person.FirstName and Person.LastName in //Textboxes on my page } ``` how can I do that? Can this be done by using and ajax call? ``` $.ajax({ type: url: success: } }); ``` any help is greatly appreciated Thanks