2012-04-13 19 views
2

我正在研究一个asp.net mv3应用程序。Jquery/ajax从一个类中获取对象,并在我的视图中的文本框中使用它

在一个辅助类,我有一个返回的人的对象基于他的ID

public Person GetPersonByID(string id) 
{ 
    // I get the person from a list with the given ID and return it 
} 

在视图中我需要创建一个jQuery或JavaScript函数可以调用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 
} 

我该怎么做?

这可以通过使用和ajax调用?

$.ajax({ 
      type: 
      url: 
      success: 
      } 
     }); 

任何帮助是极大的赞赏

感谢

回答

11

Javascript或jQuery的为此事不知道什么是method手段。 jQuery不知道C#是什么。 jQuery不知道ASP.NET MVC是什么。 jQuery不知道.NET类是什么意思。 jQuery不知道.NET类是什么意思。

jQuery是一个javascript框架,可以用来发送AJAX请求到服务器端脚本。

在ASP.NET MVC中,那些服务器端脚本被称为控制器动作。在Java中,这些被称为servlet。在PHP中 - PHP脚本。等等...

所以,你可以写,可以使用AJAX来查询的控制器操作和将返回Person类的JSON序列化实例:

public ActionResult Foo(string id) 
{ 
    var person = Something.GetPersonByID(id); 
    return Json(person, JsonRequestBehavior.AllowGet); 
} 

然后:

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); 
     } 
    }); 
} 

这显然假定您的Person类有FirstNameLastName属性:

public class Person 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 
+0

我想学这个,因为我在做一些非常相似。在你的'.ajax'中,'id'字符串的值是在哪里设置的?那将会传递给'ActionResult'方法的东西是否正确?另外,如果我的ActionResult方法没有或不需要输入参数呢? – 2015-09-17 17:42:15

1

当然可以!所有你需要在你的服务器端代码来执行,特别是在控制,是返回序列化为一个JSON对象的人,像这样:

[HttpPost] 公众的ActionResult GetPersonByID(字符串ID) { 返回JSON (人); }

在AJAX

然后,

 $.ajax({ 
      type: "POST", 
      url: form.attr('action'), 
      data: form.serialize(), 
      error: function (xhr, status, error) { 
       //... 
      }, 
      success: function (result) { 
       // result.FirstName 
      } 
     }); 
相关问题