简体   繁体   中英

Display list in asp.net MVC view

I receive a List of objects in my controller from my asp.net web application. How can I pass this list to the view2 and display it?

Controller

public class HomeController:Controller
{
 public ActionResult Index()
 {
  WCF.CommunicationServiceClient Client = new WCF.CommunicationClient("BasicHttpBinding_ICommunicationService");
  List<object> objectlist = Client.GetList("_something_");

  return View("ShowView");
 }
}

My biggest Problem is that this "object" is defined in another solution.

You need to pass the objectlist as view model to the view. I think the dynamic class will come in handy when defining your @model on the view.

Basic MVC really.

创建一个强类型的视图,然后像return View(objectlist );一样将对象传递给它return View(objectlist );

You can use the dynamic instead of Object in the List like this, As you don't know what the object have grab.

 public class HomeController:Controller
 {
   public ActionResult Index()
    {
     WCF.CommunicationServiceClient Client = new WCF.CommunicationClient("BasicHttpBinding_ICommunicationService");
     List<dynamic> objectlist = Client.GetList("_something_");
     return View("ShowView");
    }
 }

Know more about dynamic click here Also one other Question that may be relates List with Dynamic Object Type

My biggest Problem is that this "object" is defined in another solution.

You should define your object in another project. For example, 'DataTransferObjects'. Then you add a reference to this project in both your WCF Server project and your MVC (WCF Client) project. This way the class will be known by both.

In your DTO project:

[DataContract]
public class MyClass
{
    [DataMember]
    public int MyProperty { get; set; }
}

Then your code would be:

public class HomeController:Controller
{
 public ActionResult Index()
 {
  WCF.CommunicationServiceClient Client = new WCF.CommunicationClient("BasicHttpBinding_ICommunicationService");
  List<MyClass> objectlist = Client.GetList("_something_");

  return View("ShowView", objectlist);
 }
}

And your ShowView:

@model List<MyClass>

@for (i = 0; i < Model.Count; i++)
{
    @Html.EditorFor(m => Model[i].MyProperty)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM