Render strongly type partial view in layout MVC4 razor - asp.net-mvc-4

I have some issues with rendering strongly type partial view in layout view.
partial view (menu) is band with model Menu
this partial view I want to render in _layout.chtml, so it 'll be avliable in all views.
I want to make avalible the partial view(menu) in all pages/view. the problem I face is where to put the action for partial view to populate it from DB on page load.
thanks
---------------------- My code is--------------------
partial view inside shared folder.
#model List<Menu>
#foreach(var item in Model){// here is the html/model item inside to display}
--------------------------------------
HomeView.chtml inside home folder
#model List<homemodel>
.... here goes html code/ plus homemodel loop/data etc.
------------------------------
HomeController{
public ActionResult HomeView()
{
.........return view();
}
public PartialViewResult partialmenu()
{
// data from db
return partialview(partialobject as list);
}
------------------------
layoutview.chtml
--html code---
{# Html.renderpartial("partialview");}
.. html code...

I want to make available the partial view(menu) in all pages/view. the problem I face is where to put the action for partial view to populate it from DB on page load.
Write in layout: Html.RenderAction('MyMenu') OR Html.Action('MyMenu') and then populate it from any source. Your action will return strongly typed model.

where to put the action for partial view to populate it from DB on
page load.
every view has it's own controller..regardless if it is partial or not...therefore you could populate your view on it's own controller...

Related

How Can I Render A Partial View Inside an Editor Template?

I am using an edit template for Kendo scheduler called ScheduleEditorTemplate.cshtml which his located in Views/Shared/EditorTemplates
I have a partial view named _POC.cshtml and I need to display that partial view inside the ScheduleEditorTemplate.cshtml. This is a read-only partial view, the user will only view what is there.
When I use the RenderPartial method as follows I get an "invalid template" exception when I try to open the ScheduleEditorTemplate.cshtml from the scheduler. It works without the partial view included.
How can I render a partial view with a different view model into an editor template?
Here's my code to render the partial view within the ScheduleEditorTemplate.cshtml
#{Html.RenderPartial("_POC");}
I am already using this partial view in another view so I know it loads and works correctly there.
I tried this also with the same exception generated:
#Html.Partial("~/Views/EmployeeSchedule/_POC.cshtml")
I can share the code from _POC.cshtml but there's nothing special there; just kendo controls.
#{Html.RenderPartial("_POC");}
And use Ajax to load this partial view:
<script type="text/javascript">
$(document).ready(function () {
$("#div").load('#(Url.Action("POC","ControllerName"))', function(){});
});
</script>

MVC4 using same partial view in multiple views

I have a view "Register Application", containing 20 fields. The user registers. After user registered I have an option for user to update components that were submitted.
for example: view Register has sections "Contact Information" , "Address Information" ...etc currently have 5 sections.
so in the Register view I create a viewmodel #model ViewModels.RegisterVMwith all the fields.
and for edit contact information, I have its own #model ViewModels.ContactInformationVM
Now, here is my question since both views will have the same markup code I decided to create a partial view for Contact Information so I can reuse the markup code and will be able to manage it in one place instead of two places.
So in the Register view
#model ViewModels.RegisterVM
.......
#Html.Partial("~/Views/Shared/widget/_ContactInformation.cshtml", #Model)
and in the Contact Information view I want to reuse this partial view
#model ViewModels.ContactInformationVM`
#Html.Partial("~/Views/Shared/widget/_ContactInformation.cshtml", #Model)
Both views have its own viewmodel and the partial view will only be able to accept one viewmodel
No idea what viewmodel I should declare in the partial view
I know I can just copy the code from the partial view and place in the Register view and in the Contact Information view and it would work and solve the issue.. but was wondering if there a better approach to avoid having same code in multiple files.
I hope it makes sense what I am asking. Thanks for reading.
What you want to do here is create a composite view model that has each section as a separate property. For example:
public class RegisterVM
{
public ContactInformationVM ContactInformation { get; set; }
public AddressInformationVM AddressInformation { get; set; }
...
}
Then in your partial(s), you reference the sub-model:
_ContactInformation.cshtml
#model ViewModels.ContactInformationVM
<!-- contact info fields here, for example: -->
#Html.EditorFor(m => m.FirstName)
...
Then, in your register view, you use RegisterVM as your model and load the partials for each section:
#model ViewModels.RegisterVM
#Html.Partial("_ContactInformation", Model.ContactInformation)
#Html.Partial("_AddressInformation", Model.AddressInformation)
...
Now, you can reuse these components at will.

submit form from one model to another view in Yii

How do I post from one controller into another view?
I have a Review model and a Product model. The Review form is displayed in the Product view through a widget, but how do I submit the form itself? Right now, it doesn't do anything. I can submit through review/create, but not through the Product View.
Or am i suppose to do the post in the widget?
You can achieve it if you put code like below on components/ReviewWidget.php . I supposed you have Review as model and its respective controller and views file on default locations.
<?php
class ReviewWidget extends CWidget{
public function init() {
return parent::init();
}
public function run(){
$model = new Review;
if (isset($_POST['Review'])) {
$model->attributes = $_POST['Review'];
$model->save();
}
$this->renderFile(Yii::getPathOfAlias('application.views.review'). '/_form.php',array(
'model' => $model,
));
}
}
Then, call above widget on any where on view like below ,
<?php $this->widget('ReviewWidget'); ?>
It will handle item creation only. You have to create code to item update by yourself.
In your controller action you must use function renderPartial
$this->renderPartial('//views/reviw/_form',array('data' => $data ) );
First argument of this function is used to determine which view to use:
absolute view within a module: the view name starts with a single slash '/'. In this case, the view will be searched for under the
currently active module's view path. If there is no active module,
the view will be searched for under the application's view path.
absolute view within the application: the view name starts with double slashes '//'. In this case, the view will be searched for
under the application's view path. This syntax has been available
since version 1.1.3.
aliased view: the view name contains dots and refers to a path alias. The view file is determined by calling
YiiBase::getPathOfAlias(). Note that aliased views cannot be themed
because they can refer to a view file located at arbitrary places.
relative view: otherwise. Relative views will be searched for under the currently active controller's view path.
Also you can use this function in your views. But the most convenient way to reuse views is to create widgets.

MVC 4.0 using Razor view

How to set the Label Text which is available on _Layout.cstml from different Controller.
For Example
If I want to navigate from Dashboard to ProductList Page. Then My Label Text on _Layout Page should be "Product List". which I am setting from ProductList Controller Index Method.
Thanks in advance.
Use the ViewBag.xyz in _Layout.cshtml. Pass the viewdata from controller action and it will be shown on your html page.
Note:- Please confirm me if you means something else. I will update my answer if this doesn't means what you looking for.
it's look like you want to set the ViewBag.Xyz different different for every controller.
I recommanded you to use ActionFilterAttribute to make it work. The code will something like this.
public class DashboardCustomData : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Controller.ViewBag.xyz = "This is my Dashboard page";
base.OnActionExecuting(filterContext);
}
}
Now put this Actionfilter to every controller. You need to use different different ActionFilter for every controller which have different title. After doing this you never need to set it manually from every controller.
If you don't like to write the multiple filter then try this one.
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string controllerName = filterContext.RouteData.Values["Controller"].ToString();
string ActionName = filterContext.RouteData.Values["Action"].ToString();
if (controllerName == "Dashboard")
{
filterContext.Controller.ViewBag.xyz = "This is my Dashboard page";
}
else
{
}
base.OnActionExecuting(filterContext);
}
You make BaseViewModel class with that prop, set _Layout's model as this type and derive other models from it. Now you can access that prop from any derived model
You use ViewBag or ViewData
You make a #section in Layout view and populate it within Controller's views
If you need Layout's fields in many controllers then usage of #1 looks preferred.
Why does not use this simple approach:
#{
ViewBag.Name = "...";
Layout = "_Layout.cstml";
}
And in your layout set your lable text with #ViewBag.Name
Layout
<label>#ViewBag.Label</label>
Then just assign a value to ViewBag.Label in your controllers, and it will automatically change.
public ActionResult OtherPage()
{
ViewBag.Label = "Other Label";
}
Solution you have suggested works when I am on the same Controllers View but here I want to Change the Text of Controller on Master Page.
In Asp.net We use Master Page Reference on Child Page then we can
easily Change the Text, but how do i do same in MVC... Hope you
understood the scenario. –
If you look at what is generated when you start a new project with the "Internet Template" in MVC 4, you have a way to do it already working for you:
In the element of _Layout, look for <title>#ViewBag.Title - My ASP.NET MVC Application</title>, then in all the different views, you have something like this:
#{
ViewBag.Title = "Contact";
}
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
<h2>#ViewBag.Message</h2>
</hgroup>
All you need to do is to move/duplicate ViewBag.Title out of the HEAD intot the BODY, or create your own ViewBag variable, and set it's values from your different views. Obviously you could just as well set the value from the controller, but I don't see the need, as this really has to do exclusively with the user interface, which is the Views job.
Finally, if I may, don't try to duplicate in MVC what you're used to with ASP.NET. The paradigms are way too differents, chances are that you are going to waste time while there might be an easy MVC way to achieve the same thing.
It seems to me this is just an example of it.....

ASP.NET MVC 4 - _Layout Master pages loading in views not configured to do so

In my ASP.NET MVC 4 application, I have created a view (not a partial) that shows only a grid of data for printing. This acts as a print-safe view. This is enabled by a simple tag that sends you to the view. The problem is, the master page layouts are being loaded in the view.
Is there anywhere in an ASP.NET MVC 4 app, that could be secretly configuring my views to include the master _layout?
Yes. check your ~/Views/_ViewStart.cshtml file, you may find something like this:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
You can override it in your View though:
#{
Layout = null;
}
Or if your View is rendered through an Action, try to return PartialView() instead of View():
public ActionResult RenderGrid()
{
...
return PartialView(); // return View without invoking _ViewStart.cshtml
}
If you have a non-partial view, and unless you override the layout, whatever is configured in _ViewStart.cshtml will be used. You can override this by adding this to your view:
#{
Layout = null;
}
Since my _Layout was entirely in 1 element, i was able to use javascript to hide it. This not the answer I like, because its not a solution, it is a cheap work around.