代码之家  ›  专栏  ›  技术社区  ›  Tony

ASP.NETMVC将字符串对象传递到视图中的问题

  •  5
  • Tony  · 技术社区  · 15 年前

     <%@ Page Title="" Language="C#" 
         MasterPageFile="~/Views/Shared/Site.Master"
         Inherits="System.Web.Mvc.ViewPage<String>" %>
    
       <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    
              <h2><%=Model %></h2>
    
       </asp:Content>
    

    当我尝试这个:

     return View("SomeView", "stringToPass");
    

    找不到视图“SomeView”或其主视图。

    return View("SomeView");
    

    一切正常。那么如何传递那根弦呢?

    6 回复  |  直到 15 年前
        1
  •  4
  •   p.campbell    15 年前

    为此使用ViewData。在控制器中,只需设置键/值对:

    ViewData["Foo"] = "bar";
    

    然后在您的视图中,只需按之前设置的方式访问它:

    <h2><%=ViewData["Foo"]%></h2>
    

    你的问题是 View() 方法的两个参数是:视图名和主控形状名。

        2
  •  11
  •   eglasius    15 年前

    return View("SomeView", (object)"stringToPass");
    
        3
  •  3
  •   Pharabus    15 年前

    那怎么办

     ViewData.Model = "StringToPass";
     return View("SomeView");
    
        4
  •  2
  •   Parrots    15 年前

        5
  •  2
  •   RememberME    15 年前

    return View("StringToPass");
    

    如果您使用不同的操作方法:

    return RedirectToAction("SomeView", new { x = "StringToPass" });
    

    编辑 我猜选项1对字符串不起作用。我从未尝试过b/c我总是使用ViewModels:

    public class UserAdminViewModel
        {
            public string UserName { get; private set; }
    
            public UserAdminViewModel(string userName)
            {
                UserName = userName;
            }
        }
    

    return View(new UserAdminViewModel("StringToPass"));
    
        6
  •  0
  •   TheTechGuy    12 年前

    旧问题,但我将给出一个示例,说明如何使用模型将字符串传递给视图(不使用已经回答的Viewbag)

        // Action Method inside controller
        public ActionResult Index()
        {
            string msg = "Hello World";
            return View("Index","",msg); // notice the blank second parameter
        }
    
        // This goes inside the Index View
        // Will print, The Message is: Hello World
        The Message is: @Model.ToString()