Nothing
Nothing

Reputation: 2642

select new in linq c#

I have one action in my controller of asp.net mvc project.

public JsonResult GetProductBySearch(string Q)
{
   JsonResult jr = new JsonResult();
   var _product = from a in DataContext.SearchItem(Q)
                  select new { ID = a.ID, ProName = a.Name };
   jr.Data = _product.ToList();
   jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
   return jr;
}

I want to return this json data to the view of my project. It is works well in my view if I used "select new", But as I know, select new is using while we need the sub set of data. But in this query I want to get all the field from my table as below :

public JsonResult GetProductBySearch(string Q)
{
  JsonResult jr = new JsonResult();
  var _product = from a in DataContext.SearchItem(Q)
                 select a;
  jr.Data = _product.ToList();
  jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
  return jr;
}

This is what I loop in view, It is work very well if I used with select new. But when I change to SELECT, the alert is not work.

 $.getJSON(url, data, function (data) {
     alert(1);
   $.each(data, function (index, proValByDep) {

   });
 });

Any ideas please.

Upvotes: 0

Views: 1855

Answers (2)

joshuahealy
joshuahealy

Reputation: 3569

I'm just going to guess the problem as the question is a little unclear.

In the first example we see:

select new { ID = a.ID, ProName = a.Name };

In the second one the fieldnames won't be the same, so instead of ProName the resulting json will have Name.

Perhaps the javascript is expecting ProName and erroring out because it is undefined.

This doesn't explain why alert(1); doesn't work though.

Upvotes: 1

Krishnanunni Jeevan
Krishnanunni Jeevan

Reputation: 1759

why using "from a in DataContext.SearchItem(Q) select a"?

Can't you use jr.Data=DataContext.SearchItem(Q).ToList()

Upvotes: 1

Related Questions