Difference between revisions of "Using partial with controller"

From Logic Wiki
Jump to: navigation, search
(Created page with "Category:MVC Category:CSharp Category:Razor == Controller and Action == <pre class="brush:csharp;"> public class MyController { public ActionResult Index() {...")
 
 
(One intermediate revision by the same user not shown)
Line 10: Line 10:
 
   }
 
   }
 
    
 
    
−
  [ChildActionOnly]
+
        [ChildActionOnly]
−
  public ActionResult Menu() {
+
        public ActionResult _ApplicationStateMessage()
−
    var menu = GetMenuFromSomewhere();
+
        {
−
      return PartialView(menu);
+
            var model = State.Get(MyApp.UserId);
−
  }
+
           
 +
            return PartialView(model);
 +
        }
 
}
 
}
 
</pre>
 
</pre>
  
 
== Partial View ==
 
== Partial View ==
−
The Menu action grabs the Menu model and returns a partial view with just the menu.
 
 
<pre class="brush:csharp;">
 
<pre class="brush:csharp;">
−
 
+
@model PlatformModels.ApplicationState
−
<%@ Control Inherits="System.Web.Mvc.ViewUserControl<Menu>" %>
+
<div>
−
<ul>
+
    @foreach (var msg in Model.ApplicationStateMessages)
−
<% foreach(var item in Model.MenuItem) { %>
+
    {
−
  <li><%= item %></li>
+
        <div>
−
<% } %>
+
            @($"{msg.Title}")
−
</ul>
+
        </div>
 +
        <div>
 +
            @($"{msg.Content}")
 +
        </div>
 +
    }
 +
</div>
 
</pre>
 
</pre>
  
 
== View ==
 
== View ==
 
<pre class="brush:csharp;">
 
<pre class="brush:csharp;">
−
<%@ Page %>
+
@Html.Action("_ApplicationStateMessage")  
−
<html>
+
−
<head><title></title></head>
+
−
<body>
+
−
  <%= Html.Action("Menu") %>
+
−
  <h1>Welcome to the Index View</h1>
+
−
</body>
+
−
</html>
+
 
</pre>
 
</pre>

Latest revision as of 09:30, 11 May 2017


Controller and Action

public class MyController {
  public ActionResult Index() {
    return View();
  }
  
        [ChildActionOnly]
        public ActionResult _ApplicationStateMessage()
        {
            var model = State.Get(MyApp.UserId);
            
            return PartialView(model);
        }
}

Partial View

@model PlatformModels.ApplicationState
<div>
    @foreach (var msg in Model.ApplicationStateMessages)
    {
        <div>
            @($"{msg.Title}")
        </div>
        <div>
            @($"{msg.Content}")
        </div>
    }
</div>

View

 @Html.Action("_ApplicationStateMessage")