c# - Returning multiple views in one - c#

I am currently trying to display one of my views (partial view) inside of another one. Inside of my view, I have been using the following code: #{ Html.RenderPartial("_Pending"); }.
My partial view is inside of my Shared folder. My goal is to pull in two different views using logic from two different controllers. Given my two views (Transaction Index and Pending Transactions (partial)), I essentially want both of these to appear on the same page. The issue is that currently, I am essentially getting the same view twice.
In short, how do I display a partial view inside of another view, with the partial view returning results from a different controller?

If I understand correctly, what you want is getting result of same partial view but executed by two different controller.
Have you tried #Html.Action?
essentialy it is the same concept as calling Partial but with controller action involved.
to use it, just create two Action then call #Html.Action in your view, such as:
in your controller:
public ActionResult Action1() {
return PartialView("__Pending");
}
public ActionResult Action2() {
return PartialView("__Pending");
}
in your view - you can also call it within your partial view
#Html.Action("Action1")
#Html.Action("Action2")
More info abount Partial and Action difference check out
MVC Html.Partial or Html.Action
more info about hwo to use Html.Action
How can I use Html.Action?

The partial is always included in the main view. The only time you would return the partial on its own would be if you were updating via AJAX. Presumably you would use a partial to display a list of clients. You would, perhaps, use a foreach loop in your view to iterate over the lists (contained in the view model), passing each one to the partial as its model.
Find an example to use many partial views inside one view.
In aspx page:-
<asp:content id="content" contentplaceholderid="CenterContentPlaceHolder" runat="server">
<form id="frmCheckout" name="frmCheckout" method="post">
<div class="rzccartcont">
<%this.Html.RenderPartial("CheckoutProduct", Model);%>
<div class="rzcchkpmnt rzcchkpmnt-bg" id="divChkbottomArea">
<% this.Html.RenderPartial("CheckoutCartProfileInformation", Model); %>
<%this.Html.RenderPartial("CheckoutCartPaymentDetails", Model); %>
</div>
</div>
</form>
</asp:content>
Reloading part of a page via AJAX (note partial is rendered inline in initial page load)
<script type="text/javascript">
$(function() {
$('#someButton').click( function() {
$.ajax({
url: '/controller/action',
data: ...some data for action...,
dataType: 'html',
success: function(data) {
$('#partial').html(data);
},
...
});
});
});
</script>
Controller for AJAX:-
public ActionResult Action(...)
{
var model = ...
...
if (Request.IsAjaxRequest())
{
return PartialView( "Partial", model.PartialModel );
}
else
{
return View( model );
}
}
Hope it helps you.

Related

Find URL submit path of a Razor inherited page controller method

Usually, I send data to a controller with a URL using the class name followed by the method name /Parent?handler=InitData or /Parent/InitData if the #page "{handler?}" is defined in a page.
However, how can this be done with a child controller than inherits the main parent controller ?
What I am looking for is to call a method inside a child controller with a syntax that is similar to this /Parent/Child/Test. Note that the call is made within a partial page embedded inside the main parent page.
Any idea on how this can be achieved ? (I know it has something to do with routing but I just don't understand how to do it)
Here is what I have so far
Partial page
#using App.Models.PagesViews.PartialPage
#model PartialPage // <-- partial parent model has access to PartialPage_Add and PartialPage_Delete children
<script type="module">
$.ajax({
url: "/Parent/Child/Test", <-- should call child controller method but is not working!!!
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "json",
...
});
</script>
<div>
<!--... html code...-->
<div>
Parent page
#page "{handler?}"
#model App.Pages.ParentModel
#section head {
...
}
<div>
<partial name="_PartialPage" model="Model.partialPage_Add"
...
<partial name="_PartialPage" model="Model.partialPage_Delete"
</div>
Parent page controller
public class ParentModel : PageModel
{
private readonly DatabaseContext _dbContext;
public readonly PartialPage_Add partialPage_Add; // <-- PartialPage_Add is a child of PartialPage
public readonly PartialPage_Delete partialPage_Delete; // <-- PartialPage_Delete is a child of PartialPage
public MainModel(DatabaseContext _dbContext)
{
this._dbContext = _dbContext;
}
public IActionResult OnGet() => Page();
}
Child page controller
public class ChildModel : ParentModel
{
public ChildModel(DatabaseContext _dbContext) : base(_dbContext)
{
}
public void OnPostTest() // <-- Access this method from partial page
{
Log.Debug($"Successfully called method Test() in class ChildModel");
....
}
}
I think you may misunderstand the usage of Razor Pages and MVC Controller.
Razor Pages should contains .cshtml file declared with #Page and .cshtml.cs file with same name of the .cshtml file. Also the .cshtml.cs file should inherits PageModel or the inheritance class of the PageModel.
Your ChildModel extends the ParentModel which is the inheritance class of PageModel, if your project does not contain corresponding .cshtml, the ChildModel is just a simple class and cannot be called by ajax.
So you need be sure your project contains a Child.cshtml and declare #page "{handler?}" in it. And then the correct url should be /Child/Test.
If you want to use the parent as the suffix, change the page route template to #Page "/Parent/Child/{handler?}".
Besides, you must send the AntiForgeryToken together with the data you want to the Post method if you use ajax in Razor Pages.
Reference:
How to take result value of a jQuery script into a C# code in the same razor page in ASP.NET Core MVC?
For MVC controller, no matter your project contains the .cshtml file or not, you can also hit the action, because you can configure the route template in the Startup.cs/Program.cs or just use [Route] attribute.

MVC 4 get data from Parent from Partial View

I have a case like the following:
The Parent page looks like:
#using (Html.BeginForm("Create", "HTML", FormMethod.Post))
{
#Html.DropDownListFor(model => model.SelectedObjectId, Model.MajorObjects)
#Html.Partial("_SelectCase");
...
}
And in the _SelectCase i want to load some data based on the DropDownList selected element.
For this i have the _SelectCase like
#using (Html.BeginForm("SelectCase", "HTML", FormMethod.Post))
{
...
}
And the controller like
public ActionResult SelectCase(CustomIdentity currentUser)
{
...
}
And the question: how may i get the value from the DropDownlist in the SelectCase method from the Controller?
Thanks.
As far as I know, you can't have a dynamic partial inside a parent.
Parent and Partial views are generated after a server side call.
The best you can do is make that partial form in the parent and have whatever values you want to change dynamically fetched through an AJAX call.

Retrieve data from partial view on post request via jQuery

I have a view that dynamically updates depending on user input - here's how it works:
View is rendered with initial data from controller populated with a partial view
When something is clicked, I use retrieve a partial view from an ActionResult from the controller and replace existing data with jQuery
I need a string from the controller for the main view, so I make another call to the controller and retrieve a string.
I want to know if there's a way to get the string I need with the partial view instead of making a separate controller call.
Initial Data:
<!-- This needs to change when the partial is replaced, but it's heavier html
and I don't want to include it in the partial to minimize server calls/data -->
<div class="Location"> </div>
<div class="myContainingDiv">
<!-- This content gets updated -->
#Html.Partial("_MyPartial");
</div>
Partial View:
<div class="something">Model.something</div>
Controller Method (Partial View):
[HttpGet]
public ActionResult _MyPartial(string param1)
{
MyModel model = new MyModel();
// This is dynamic and what I need to get in my main view from the partial view
model.something = "Hi";
return PartialView(model);
}
Controller Method (Return desired string):
public string GetHiString(string param1)
{
return "Hi";
}
JavaScript (Update partial view):
$.post('/Home/_MyPartial', { 'param1': 'Hi' }, function (result) {
$('.something').replaceWith(result);
getOtherThing('Hi');
});
JavaScript (getOtherThing):
$.post('/Home/_GetHiString', { 'param1': 'Hi' }, function (result) {
$('.Location').replaceWith(result);
});
OK, i think that's everything.
Basically I only want to hit the controller once per call. Including the div in the partial view is not an ideal option.
I hit the controller the second time from my main view to get data that can easily be created from an object within the first method and sent down to the partial view.
So, besides including <div class="Location"> in my partial view, is there a way to send the extra information I need to the partial view and retrieve it dynamically from my main view (via JavaScript). Or is there a way to return additional data when I call _MyPartial from my JavaScript?
This is really the last simplification I want to make and i'd really appreciate the help!
You could modify your partial view _MyPartial and it's model to include something hidden within it that you could extract using jQuery:
Partial View
<div class="something">Model.something
<input class="somethingElse" type="hidden" value="#(Model.somethingElse)" />
</div>
Controller Method (Partial View):
[HttpGet]
public ActionResult _MyPartial(string param1)
{
MyModel model = new MyModel();
// This is dynamic and what I need to get in my main view from the partial view
model.something = "Hi";
model.somethingElse = GetHiString(param1);
return PartialView(model);
}
JavaScript (Update partial view)
$.post('/Home/_MyPartial', { 'param1': 'Hi' }, function (result) {
$('.something').replaceWith(result);
$('.Location').html($('.somethingElse').val());
});

MVC2 Partial View, Search Control - Design / Implementation

I have a partial view that is a search textbox and button.
I am trying to make it a partial view so that I can render it in several places. When the user clicks search I want it to redirect to /Home/Search which will show a list of items based on what was put into the search box.
Is this the right approach or should I make the form just run the /Home/Search Index() action and not have a partial view controller at all?
Partial View
<% using (Html.BeginForm("Search", "SearchBox")) {%>
<%: Html.TextBoxFor(model => model.searchTerm) %>
<input type="submit" value="Search" />
<% } %>
Partial View Controller
public class SearchBoxController : Controller
{
public ActionResult Search(ViewModels.SearchViewModel item)
{
Models.DataClasses1DataContext db = new Models.DataClasses1DataContext();
List<Models.Item> retVal = (from p in db.Items
where p.Name.Contains(item.searchTerm)
select p).ToList();
return RedirectToAction("Search", "Home"); //No data... What to do????
}
}
or should I make the form just run the /Home/Search Index() action and not have a partial view controller at all?
Definitely yes. That's all, there is no real need for the partial controller, specially if it involves an extra redirect.

Using the same code in different (partial) views

Maybe this question is quite simple because I'm new to MVC2. I have a simple demo MVC project.
(1) A weak-typed view: Index.aspx
<% Html.RenderPartial("ArticalList", ViewData["AllArticals"] as List<Artical>); %>
(2) A strong-typed partial view: ArticalList.ascx
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<List<Artical>>" %>
<% foreach (Artical a in Model) { %>
<%= Html.ActionLink(a.Title, "About", new { id = a.ID })%><br />
<%} %>
(3) Here is the HomeController.cs
public ActionResult Index()
{
ViewData["AllArticals"] = Artical.GetArticals();
return View();
}
public ActionResult ArticalList()
{
return PartialView(Artical.GetArticals());
}
Sorry I'm using a Web-Form "angle", because if I'm using a Web-Form, when I visit Index.aspx, rendering ArticalList.ascx will call public ActionResult ArticalList(). But here I need to write Artical.GetArticals() twice in two actions. How can I put them in one?
From what I understand, as a recent newbie in MVC too, is that the partial view does not use a action method in a controller. The "ArticalList" is a reference to the partial view file only and does not make another request for an action method. The partial view gets all of it's data from the view it is called from.
Html.RenderAction might be the behavior you're getting confused with.

Categories