我是Ajax的新手,我正在尝试使用jquery通过ajax调用从数据库中获取数据。
我有一个国家/地区标签列表,我正在尝试在有用户操作时显示数据
这是我的代码示例,目前它说有一个空系统引用。
public ActionResult Details(int id, string searchTerm)
{
// Do we have a search term
if (!String.IsNullOrEmpty(searchTerm))
{
// decode the searchTerm as we dont want to search for encoded bits
searchTerm = Decode(searchTerm);
}
var a = _mRepository.GetMyId(id);
if (a == null)
{
return View("NotFound");
}
// Here we need to get list of countries for the selected manufacturer
var c = _mwRepository.Getcountries(id);
ViewData["Countries"] = c.ToArray();
// Now we need list of products for the manufacturer countries and this is an Ajax call to database so that it fetches data only when there is a user action
foreach (var country in c)
{
var p = _productRepository.GetAllCurrentProductsForManufacturerCountry(id,
country.Id);
}
if(Request.IsAjaxRequest())
{
ViewData["ManufacturerCountryProducts"] =
p.ToArray();
}
答案 0 :(得分:2)
public class CountryProducts
{
public Country Country { get; set; }
public List<Product> ProductsList { get; set; }
}
[HttpPost]
public ActionResult Details( int id, string searchTerm )
{
// Do we have a search term
if ( !String.IsNullOrEmpty( searchTerm ) )
{
// decode the searchTerm as we dont want to search for encoded bits
searchTerm = Decode( searchTerm );
}
var a = _mRepository.GetMyId( id );
if ( a == null )
{
return View( "NotFound" );
}
// Here we need to get list of countries for the selected manufacturer
List<Country> countriesList = _mwRepository.Getcountries( id );
var data = new List<CountryProducts>();
if ( countriesList != null )
{
foreach (var country in countriesList)
{
List<Product> products = _productRepository.GetAllCurrentProductsForManufacturerCountry(id,
country.Id);
data.Add(new CountryProducts() {Country = country, ProductsList = products});
}
}
if (Request.IsAjaxRequest())
{
ViewData["CountryProducts"] = data.ToArray();
}
}
但我对ajax使用了两种不同的方法,例如:
public ActionResult Details( int id )
{
...
return View(model);
}
//for ajax request:
[HttpGet]
public JsonResult Details( int id, string searchTerm )
{
return new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = GetFilteredDetailsData(id, searchTerm)
};
}