Returning Partial View ASP.NET MVC - c#

Hi I have a partial view setup for handling error messages, but when it's returned it returns a full webpage with just the text No Results Found.
I would expect the Partial View to return inline on my main Index page? As in my Index page I have the code #Html.Partial("_ErrorMessage").
Below is how I'm handling this in my HomeController
else
{
ViewBag.Error = "No results found!";
return PartialView("ErrorMessage");
}
}

Partial view not necessary return html inline. Partial view can return html inline if you call by client script, using jquery, angular, etc.
This way did you make. The return is a whole page.

Context is important here. If you are including the partial view in line in the HTML, you probably don't need to return the partial view in C-sharp unless you're using a fancy asynchronous call to load it.
The in-line partial view should display normally if you just show the view where it was included

I am not sure what the exactly error you are facing but you can try following solution, you have to set Layout as null after you will not facing the full page on your partial view.
#{
Layout = null;
}
If you are not using Layout=null it will call your _Layout page.
Hope it helps you.

Related

partial view not displaying but its viewmodel works on parent

In the cshtml code header I've instantiated a viewmodel with some data. I can bind to and display data from that viewmodel variable in the parent page. However, when I pass the viewmodel variable into a child partial view, nothing displays on the page.
#{
Html.Partial("DailyReport", #DailyReportViewModel);
}
Any idea why the child partial view would not be displaying on the page or how to debug this issue?
Because you are calling the Partial method which return an MvcHtmlString, but you are not using the return value of the method.
You can do this instead
#Html.Partial("DailyReport", #DailyReportViewModel);
Razor will now render the return value from the DailyReport method.
Or you can use the RenderPartial method which render the result.
#{
Html.RenderPartial("DailyReport", DailyReportViewModel);
}
Assuming DailyReportViewModel is an object of type T to which your partial view is strongly typed to.
Put # at the front and remove the # from DailyReportViewModel and it should work.
#Html.Partial("DailyReport", DailyReportViewModel);

Sending Temporary data to multiple partial views from view MVC

I'm wondering if there is a good way to do this. I'm currently trying to send some temporary data to multiple partial views being called from the same view page in my MVC application.
I'm currently attempting to do this with TempData but I can see my understanding is limited as it is only going through for one partial request. What method do I need to use to filter out to all of my partials?
Main View Page:
#{
ViewBag.Title = "Main View Page";
TempData["ReturnUrl"] = Request.Url.OriginalString.ToString();
}
#Html.Partial("_StatusTable1")
#Html.Partial("_StatusTable2")
#Html.Partial("_StatusTable3")
#Html.Partial("_StatusTable4")
#Html.Partial("_StatusTable5")
Partial View Example:
#{
var temp = TempData["ReturnUrl"]; // temp is null on all partials except the first
}
// Partial View Code ...
Thanks in advance.
In your main view page call the partiel views like that
#Html.Partial("_SomePartial", TempData["ReturnUrl"])
I think that even this would work.
#Html.Partial("_SomePartial", TempData)
Get the value from TempData like this. ReturnUrl Value will retained across all the Partial Views
#{
var temp = TempData.Peek("ReturnUrl");
}
// Partial View Code

Passing a model with a Partial View

I want to show a view on some of my forms, which shows a list of alerts, read from a database table. I think I need to use a partial view - but haven't used one.
So far, I created a partial view in my shared views folder called "_Alerts.cshtml".
In that file, at the moment, I simply have:
#{
Layout = null;
}
This is a shared view.
This is just me trying to display something.
And then, on my existing page, on which I want to display the alerts, I have this section of code:
#if (User.Identity.IsAuthenticated)
{
<div class="row">
#Html.Partial("~/Views/Shared/_Alerts.cshtml", null)
</div>
}
This works. However, my understanding is not right. At the moment, I pass no model to it. Is there no controller for the partial view? At the moment, I need to create a controller method - somewhere - that gets me a list of alerts from my data service, and then I want to format that and present it in the partial view. But I am unsure where the controller methods go. If this view is called from 8 different screens, would the 8 controllers for these screens have a call to get my alerts, and format them?
Seems like a lot of duplication.
They need not be duplication.
You can define the action you want inside a controller and call #Html.Action instead of #Html.Partial
Inside you action you can return a partial view.
public class AlertsController : Controller
{
public ActionResult Show()
{
var model = GetModel();//decide where this will come from.
return PartialView("~/Views/Shared/_Alerts.cshtml",model);
}
}
In your layout view or wherever you need to use it. you can simply call it as below.
#Html.Action("Show","Alerts")
If you have all the data you need to pass into the partial, then you can use the #Html.Partial and pass in the model.
If on the other hand, you want the view you are embedding to get the data itself, then you would use Html.RenderAction

Best way to display a JQuery Dialog with ASP.NET MVC data bound View Model

Imagine a simple page with a list of users. Selecting a user displays a JQuery modal dialog with various details that can be edited. Something like:
#model IEnumerable<UserRole>
#if (Model.Any())
{
foreach (var user in Model.Users)
{
Details
}
}
I'll have more specific examples through the post but what I'm looking for is a general 'experienced' opinion on what's the best way to load and display a Model bound Partial View as a JQuery dialog box.
I know how to do it code-wise but I think there must be a better way. I believe the common known ways to do it are not very efficient.
My rule and what I would like is for all code associated to a partial view popup to be kept in that partial view. I would like my popup to be structured something like the following UserDetails partial view:
#model User
<script src="#Url.Content("~/Scripts/UserScripts.js")" type="text/javascript"></script>
<div id="placeholder">
...The modal dialog content...
</div>
This way when another developer gets to look at it one will easily be able to piece it all together.
So as far as I know there are two ways to display a partial view as a Dialog and I have a problem with both of them:
1) Use the Partial view structure I displayed above, pre-load the div dialog from the master page by using #Html.Partial("UserDetails", new User) and then, when I need the dialog to be displayed populated with user data execute an Ajax call to an ActionMethod that will re-populate the partial view's model with needed data and re-render it with JQuery .html() method.
Once the partial view/dialog is loaded with data I simply display it with JQuery .dialog('open')
Great, this works but there are a few problems with this logic:
a) I'm loading the same partial view twice ( first blank , second loaded with data )
b) Content of the Placeholder DIV flashes on the screen when the master page is being loaded. Setting DIV to display:none won't work here before when .html() method triggers it will load the partial view with that display:none tag in it and the popup will be presented as a blank window.
c) When the page is requested, if large, it takes some time for the page to show
2) Instead of having in the partial View I can place a blank <div id="placeholder"></div> on the master page and then load the partial view content into that div with ajax or as I'm doing it now with JQuery :
var url = "/MyController/MyAction/" + Id;
$("#palceholder").load(url).dialog('open');
Again, it works but there are a few big problems I see with this way:
a) It breaks my "keeping it all together rule". When looking at , without some searching around another developer will have no idea what partial view will be loaded in this Div.
b) All Javascripts for the partial view popup will now need to be referenced in the master page, instead of a the partial view itself.
c) When the page is requested, if large, it takes some time for the page to show
The bottom line question is what do you think is the best way to display the model-bound populated partial view as a Modal Dialog while keeping the code organized ?
My perfect scenario would be to pre-load all partial view fields and then, when the request is made for the dialog to show populated with Data somehow a model bind pre-loaded partial view to the new JSon set of data, without loading/re-loading all partial view fields.
Is there a way ?
P.S. One of the things I tried is to pre-load my partial view fields with #Html.Partial("UserDetails", new User) and then use JQuery .replaceWith() method to replace Div contents but I couldn't get it to work unfortunately.
Any thoughts are appreciated. No ideas as are bad ideas.
Thanks.
Nothing wrong with having part of your code load in partial, and then just updating the partial container with a return from action.
<div id="ParitalContainer">
#Html.Partial("_PartialView", Model.PartialModel)
</div>
Or, you can consider a scenario to work with JSON data. Namely, have all your data loaded async by calling a $.ajax or $.getJSON. Your action result would return JsonResult and then you can just update the elements you want.
Furthermore, you could look into using Knockout.js if you want more robust solution. This is what I would do if I wanted "keeping it all together" approach.

How to move the LoginForm to another place

I am a little stuck, how would I go about moving the login form in MVC3 C# to a self created
layout page which is done in HTML so i can position the login form in my layout instead of clicking on the login link?. I have a box in my HTML design which I would like the LOGIN page to appear in. Is this possible. If there is anything you people would require please let me know in advance thanks. So in general terms when i run my MVC3 c# application my login form appears on the same page that appears first which is my layout page. My controller has the following code:
namespace TestProject.Controllers
{
public class ViewDeveloperController : Controller
{
public ActionResult Index()
{
using (var db = new GameZoneEntities5())
{
return View(db.tblDevelopers.ToList());
}
}
}
}
I dont know if that will be helpful if there is anything else please ask.
Use a Child Action for this. A Child Action is basically just like a normal action, except that it returns a PartialView instead of a View, which you can think of as a re-usable part of page with some logic behind it. Then, all you need to do is have your layout page render the child action, via the RenderAction HTML helper method.
So, you code could look something like this
public class AccountController
{
public ActionResult LogOn()
{
return PartialView();
}
}
And your _Layout.cshtml would just need to have the following code to render the child action in the place where you want your login control to appear.
#{ Html.RenderAction("LogOn", "Account" }); }
Your LogOn view razor code would just look like normal.
Once you had that working, it would be fairly easy to make some improvements, like having the LogOn Child Action show a LogOut view if the user was already logged in, or use JQuery have the LogOn form POST the results via AJAX making the UI that much nicer.

Categories