如何在不创建多个actionresults的情况下将字符串数组从控制器传递到视图MVC4? [英] How to pass a string array from controller to the view MVC4 without creating multiple actionresults?

查看:65
本文介绍了如何在不创建多个actionresults的情况下将字符串数组从控制器传递到视图MVC4?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是mvc4的新手,所以请放轻松,我正在尝试将多个目标名称从控制器传递到我的视图.如何在不创建更多动作结果和对象的情况下执行此操作.我想使用字符串数组创建一个带有目标名称的表.这有什么可能的帮助将不胜感激.预先谢谢你.

I am new to mvc4 so please go easy, i am trying to pass multiple names of destinations from the controller to my view. How can i do this without creating more actionresults and objects. I want to create a table with the destination names using a string array. Is this possible any help would be appreciated. Thank You in advance.

Controller:
public ActionResult Destinations()       
{           
   string[] arrivalAirport = new string[4] { "london", "paris", "berlin", 
                                                          "manchester" };            

   Destination dest = new Destination();            
   dest.arrivalName = arrivalAirport[2];      

   return View(dest);
 }

Model:
public class Destination    
{        
    public string arrivalName { get; set; }    
    public string arrivalCode { get; set; }
}

View:
@model Flight.Models.Destination

@{
  ViewBag.Title = "Destinations";
  Layout = "~/Views/Shared/_Layout.cshtml";
}
<table>
    <tr>
        <td>@Html.Label("Arrival Name")</td>
        <td>@Model.arrivalName</td>            
    </tr>
</table>

推荐答案

问题的措词非常混乱,但是听起来您想将多个Destination对象传递给视图.如果是这种情况,只需将多个目标对象传递到您的视图即可.

The wording of your question is very confusing, but it sounds like you want to pass multiple Destination objects to your view. If that's the case, just pass multiple destination objects to your view.

控制器:

public ActionResult Destinations()       
{           
    string[] arrivalAirport = new string[4] { "london", "paris", "berlin", 
                                                          "manchester" };            
    var airports = new List<Destination>();

    foreach( var airport in arrivalAirport )
    {
        airports.Add( new Destination() { arrivalName = airport } );
    }   

    return View(airports);
}

查看:

@model List<Flight.Models.Destination>

<table>
@foreach( var dest in Model )
{
    <tr>
    <td>Arrival Name</td>
    <td>@dest.arrivalName</td>            
</tr>
}
</table>

这篇关于如何在不创建多个actionresults的情况下将字符串数组从控制器传递到视图MVC4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆