I have a shared view in my _Layout.cshtml for my header named "_Header.cshtml".
I would like to display text and image from the database, so I need my controller to go in the database and return it to the _Header.cshtml.
How can I do that because the controller called is always different each page the user goes. Is there a way to have controller with Shared View?
Here is the _Layout.cshtml
<div id="header">
<div id="title">
#Html.Partial("_Header")
</div>
<div id="logindisplay">
#Html.Partial("_CultureChooser")
<br />
#Html.Partial("_LogOnPartial")
</div>
<div id="menucontainer">
#Html.Partial( "_MenuPartial")
</div>
</div>
<div id="main">
#RenderBody()
<div id="footer">
</div>
</div>
</div>
In your contoller action you could specify the name of the view:
public class MenuController : Controller
{
[ChildActionOnly]
public ActionResult Header()
{
var model = ... // go to the database and fetch a model
return View("~/Views/Shared/_Header.cshtml", model);
}
}
Now in your _Layout.cshtml instead of #Html.Partial("_Header") do this:
#Html.Action("Header", "Menu")
... 1 year later would just like to add one thing to Dimitrov answer. You can make the controller a little cleaner:
public class MenuController : Controller
{
[ChildActionOnly]
public ActionResult Header()
{
var model = ... // go to the database and fetch a model
return Partial("_Header", model);
}
}
Create an action in one of your controllers to render the header view, then simply call #Html.RenderAction("Header") within the _Layout.cshtml.
You can also pass a model into the RenderAction method if required.
While the RenderAction approach that WDuffy provided works well, I recently blogged about this very topic using another approach using IoC:
http://crazorsharp.blogspot.com/2011/03/master-page-model-in-aspnet-mvc-3-using.html
I hope the question you have asked is Like....
Can we have a controller for a Shared Layout View.
Simple answer is No.
To achieve this goal you have to create a partial view for the Same purpose and put it into you shared Layout. By that means you can achieve you Goal
Related
In a ASP.NET MVC website; does every view need to have a corresponding/associated Model and Controller?
I am building the bare bones of my website; so I have created all the views but not the Models or Controllers yet. I want to be able to view a page (that contains no content associated with a model or any functionality that a controller should handle - yet). So at this point every view (cshtml page) is a static HTML page.
But when I go to access any view/page I get the error:
The resource cannot be found. Description: HTTP 404. The resource you
are looking for (or one of its dependencies) could have been removed,
had its name changed, or is temporarily unavailable. Please review
the following URL and make sure that it is spelled correctly.
Requested URL: /TeamMember/raiseIssue
raiseIssue.cshtml content:
#{
Layout = "layouts/main.cshtml";
}
<form action="#ViewBag.PostUrl" method="post">
<div class="row feedback-input text-center">
<textarea name="Text"></textarea>
</div>
<div class="row text-center">
<button type="submit" class="btn btn-default btn-standard">Submit</button>
</div>
</form>
MVC do not allows to browse the view directly. What you can do is create empty controller method like below
public ActionResult RaiseIssue()
{
return View();
}
in controller TeamMemberController
One other thing, please make sure that proper route are configured in RouteConfig.cs
I hope using this method you will be able to browser the view with writing much code in controller or model/
I have 2 Controllers
- HomeController
- Index()
- AccountController
- Login()
In my Home/Index.cshtml I want to Load The AccountController/Login method which then returns a view and displays it in my Home/Index view.
Home/Index.cshtml
<div class="row-fluid">
<div class="col-md-12">
<!-- Render the view that the AccountController/Login method denotes -->
</div>
</div>
How do I do this?
use this with your actual Controller/View names
#Html.Partial("../Home/Login", model)
or
#Html.Action("action", "controller", parameters)
I'm building a profile page that will have a number of sections that relate to a particular model (Tenant) - AboutMe, MyPreferences - those kind of things. Each one of those sections is going to be a partial view, to allow for partial page updates using AJAX.
When I click on an ActionResult in the TenantController I'm able to create a strongly typed view and the model data is passed to the view fine. I can't achieve this with partial views.
I've created a partial view _TenantDetailsPartial:
#model LetLord.Models.Tenant
<div class="row-fluid">
#Html.LabelFor(x => x.UserName) // this displays UserName when not in IF
#Html.DisplayFor(x => x.UserName) // this displays nothing
</div>
I then have a view MyProfile that will render mentioned partial views:
#model LetLord.Models.Tenant
<div class="row-fluid">
<div class="span4 well-border">
#Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml",
new ViewDataDictionary<LetLord.Models.Tenant>())
</div>
</div>
If I wrap the code inside the DIV in _TenantDetailsPartial inside #if(model != null){} nothing gets displayed on the page, so I'm guessing there is an empty model being passed to the view.
How come when I create a strongly typed view from an ActionResult the user in the 'session' gets passed to the view? How can pass the user in the 'session' to a partial view that is not created from an ActionResult? If I'm missing something about the concept, please explain.
You're not actually passing the model to the Partial, you're passing a new ViewDataDictionary<LetLord.Models.Tenant>(). Try this:
#model LetLord.Models.Tenant
<div class="row-fluid">
<div class="span4 well-border">
#Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", Model)
</div>
</div>
Also, this could make it works:
#{
Html.RenderPartial("your view", your_model, ViewData);
}
or
#{
Html.RenderPartial("your view", your_model);
}
For more information on RenderPartial and similar HTML helpers in MVC see this popular StackOverflow thread
I know question is specific to MVC4. But since we are way past MVC4 and if anyone looking for ASP.NET Core, you can use:
<partial name="_My_Partial" model="Model.MyInfo" />
Three ways to pass model data to partial view (there may be more)
This is view page
Method One Populate at view
#{
PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
ctry1.CountryName="India";
ctry1.ID=1;
PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
ctry2.CountryName="Africa";
ctry2.ID=2;
List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
CountryList.Add(ctry1);
CountryList.Add(ctry2);
}
#{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}
Method Two
Pass Through ViewBag
#{
var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}
Method Three
pass through model
#{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}
I have a simple MVC application that retrieves DB Server, database, username and password from the user to store in an XML file. I want to add a "Test Connection" button to the screen and have it execute a method on the controller called TestConnection. The problem is the TestConnection method resets all the information on the screen when clicked since the View is being returned with no model. (because a GET operation is occurring). Here is my code:
From the Controller (named FrameworkConfigurationController.cs)
public ActionResult TestConnection()
{
return View("Index");
}
[HttpPost]
public ActionResult TestConnection(FrameworkConfigurationViewModel viewModel)
{
// TODO: Test will occur here
viewModel.DbConnectionMessage = string.IsNullOrEmpty(viewModel.DatabaseName) ? "Connection unsuccessful" : "Connection successful";
return View("Index", viewModel);
}
From my View (FrameworkConfiguration/Index):
#model Framework.ViewModels.FrameworkConfigurationViewModel
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>FrameworkConfigurationViewModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.ServerName)
</div>
#* Edited for brevity *#
<button type="submit" onclick="location.href='#Url.Action("TestConnection")'">
Test Connection</button>
#Html.ValueFor(model => model.DbConnectionMessage)
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to Dashboard", "Index", "Home")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Admittedly, I am new to MVC programming. I'm coming from a Silverlight/MVVM background so the concept is not foreign to me...the disconnected nature of web programming is. I've followed some tutorials out there, but none of them seem to cover this type of thing - every example is contrived. I know how to do this with webforms and code-behind, but I would like to accomplish this with MVC.
Is there some way to "force" the POST operation instead of GET? I was under the impression that
<button type="submit">
accomplished that. Perhaps the implementation of the onclick I have written isn't correct. I am sure this is HTML 101 stuff, but I can't seem to find a simple answer to this.
Thanks for any help you can offer,
Jason
Why not have the Test Connection button trigger an Ajax action to call the controller, and display the result?
That way you avoid submitting your entire page.
In case you're not familiar with the details, here's a good overview on getting started with Ajax and MVC 4
http://ofps.oreilly.com/titles/9781449320317/ch_AJAX.html
I have never done a POST request via Razor and MVC4. I think i have the core methods and stuff down but i am having difficulty fulfilling an actual POST request.
Here is the Razor View page code...
#model UserJob
#Html.HiddenFor(Model => Model.UserCode)
#Html.DropDownList("jobCode")
<input type="submit" value="Add" class="btn btn-default" />
And the method which i want to fulfil the POST method is.....
[HttpPost]
public ActionResult AddSkill(UserJob model)
{
db.UserJobs.Add(model);
db.SaveChanges();
return RedirectToAction("Jobs", new { UserCode = model.UserCode });
}
You Razor view needs to have the form. Either use #Html.BeginForm(...) to enclose your inputs, or just write HTML form markup yourself.