0

My controller is returning following list :

public ActionResult Index()
{
    CRMDataContext mycontext=new CRMDataContext();

    var myquery = (from c in mycontext.Websites
                  select c).ToList();

    return View(myquery);
}

i'm wondering how can i loop through myquery to display its properties in view??

any suggestions for improving above code will be added advantage.

1
  • Did you try Json Result and tried to read the values in JQuery ? Commented Mar 29, 2013 at 13:37

3 Answers 3

4
@foreach(var item in Model){
  ...
}

improvement suggestions:

  • move your query in another method/class for core reusage
  • separate responsibilities by using separate models for domain and view
Sign up to request clarification or add additional context in comments.

Comments

0

You can use foreach loop:

@{
  foreach (var element in Model)
  {
      //Write you html code here.
  }
}

Comments

0

First of all it's best that you map your entity into a model and use the model in your view. Most importantly if you will not be using all the fields in your entity.

Suppose your entity has this structure:

public class Website {
  public string Title {get;set;}
  public string Url {get;set;}
  public string Description {get;set;}
}

In your view you can do something like:

@model IEnumerable<Website> // you may need to fully qualify it or add the namespace in your web.config
@foreach(var o in Model){
  <div>
     <h1><a href="@o.Url">@o.Title</a></h1>
     <p>@o.Description</p>
  </div>
}

4 Comments

When i tried your code im getting this error: foreach statement can not operate on variables of type Website because it doesnot contain a public defination for 'GenEnumerator'
Your code shows that you return a list of objects, and those objects are instances of Website. Isn't that right? I updated the model to be IEnumerable<Website>.
after changing @model header to IEnumerable im getting following error: : The model item passed into the dictionary is of type 'System.Collections.Generic.List1[ImportFromExcel.Website]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[ImportFromExcel.Models.Website]'.
i could solve it via this post : stackoverflow.com/questions/15705808/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.