I'm very new to web app development and I thought I would start with recent technology and so I'm trying to learn asp.net as-well as the MVC framework at once. This is probably a very simple question for you, MVC professionals.
My question is should a partial view have an associated action, and if so, does this action get invoked whenever a normal page uses RenderPartial() on the partial view?
While you can have an action that returns a partial view, you don't need an action to render a partial view. RenderPartial takes the partial view and renders it, using the given model and view data if supplied, into the current (parent) view.
You might want an action that returns a partial view if you are using AJAX to load/reload part of a page. In that case, returning the full view is not desired since you only want to reload part of the page. In this case you can have the action just return the partial view that corresponds to that section of the page.
Standard mechanism
Making use of partial view within a normal view (no action needed)
...some html...
<% Html.RenderPartial( "Partial", Model.PartialModel ); %>
...more html..
Ajax mechanism
Reloading part of a page via AJAX (note partial is rendered inline in initial page load)
...some html...
<div id="partial">
<% Html.RenderPartial( "Partial", Model.PartialModel ); %>
</div>
...more html...
<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 );
}
}
The accepted answer is completely correct, but I want to add that you can load your partial view using jQuery load. Less configuration needed, if you don't want to consider concurrency.
$("#Your-Container").load("/controller/action/id");
I was able to achieve something similar with this logic.
Within the .cshtml
#Html.Action("ActionMethodName", "ControllerName");
Within the controller
[Route("some-action")]
public ActionResult ActionMethodName()
{
var someModel = new SomeModel();
...
return PartialView("SomeView.cshtml", someModel);
}
And that's it.
If you need to pass values from the .cshtml to the action method then that is possible to.
The answer is no. But sometimes you need some controller action behind a partial view. Then you can create an actionMethod wich returns a partial view. This actionMethod can be called within another view:
#Html.Action("StockWarningsPartial", "Stores")
The actionmethod can look like:
public ActionResult StockWarningsPartial()
{
....
return View("StockWarningsPartial", warnings);
}
and the view 'StockWarningsPartial.cshtml' starts with:
#{
Layout = null;
}
to make it not render your surrounding layout again.
public ActionResult GetStateList(int country_id)
{
List<stateDTO> stateList = new List<stateDTO>();
stateList = bll.GetState(country_id);
ViewBag.sList = new SelectList(stateList, "state_id", "State_Name");
return PartialView("DisplayStates");
}
Related
In my MVC5 project I want to create a menu in a partial view. This menu is dynamic in the sense that it is built from content in my database. Thus I have a controller taking care of creating my menu and returning the menu model to my partial view:
public PartialViewResult GetMenu()
{
MenuStructuredModel menuStructuredModel = menuBusiness.GetStructuredMenu();
return PartialView("~/Views/Shared/MenuPartial", menuStructuredModel);
}
In my partial view called MenuPartial I want to use razor to iterate over my menu items, like:
#model MyApp.Models.Menu.MenuStructuredModel
<div class="list-group panel">
#foreach (var category in Model.ViewTypes[0].Categories)
{
#category.ShownName
}
</div>
Now the problem is the view in which I insert the partial view. If in the view I simply do:
#Html.Partial("MenuPartial")
It won't call the controller to populate the model with data first. What I want is to let the controller return the partial. But I don't know how to do this from the view. In pseudo code I would like to do something like:
#Html.RenderPartialFromController("/MyController/GetMenu")
Thanks to Stephen Muecke and Erick Cortorreal I got it to work.
This is what the controller should look like:
[ChildActionOnly]
public PartialViewResult GetMenu()
{
MenuStructuredModel menuStructuredModel = menuBusiness.GetStructuredMenu();
return PartialView("~/Views/Shared/MenuPartial", menuStructuredModel);
}
And it may called like:
#Html.Action("GetMenu", "Home")
(Hence GetMenu() is declared in the HomeController in my example).
The controller is now called (and the model is populated) prior to the partial view is rendered.
You should use: #Html.RenderAction or #Html.Action.
I have an MVC 4 View that contains a form and a partial view. The main view contains information about a product and the partial view contains images of the product.
What I would like to do is to have the partial view contain it's own form which the images would be displayed on. If I submit this form to a controller action method, modify the model it's based on and then have the action method refresh the partial view, will just the partial view section of my main view change and not the main view itself? If not, is there a better way to do what I'm trying to do. I just want to update the partial view section of the main view.
If you want to update just the Partial View, you should retrieve the data using an AJAX call. That way you call a Controller that will return you the View (in this case Partial View) that you need. Example:
CSHTML:
<div id="myPartialViewDiv">
#{Html.RenderPartial("myPartialView", Model);}
</div>
JS:
searchAdmin = function () {
var URL = "myController/myAction";
$.get(URL, { "optionalArg": optionalArg }, function (data) {
$("#myPartialViewDiv").html(data);
})
}
myController:
public JsonResult myAction(string optionalArg)
{
// do something...
return this.Json(whatIwantToReturn.ToList(), JsonRequestBehavior.AllowGet);
}
Is there a way to submit a partial view form in asp.net mvc without reloading the parent page, but reloading the partial view only to its new state? Similar to how knockout.js updates using data-bind.
My data table renders with a variable number of columns/names so I don't think knockout.js is an option for this one, so I am trying to use a partial view instead.
Not without jQuery.
What you would have to do is put your Partial in a div, something like:
<div id="partial">
#Html.Partial("YourPartial")
</div>
Then, to update (for example clicking a button with the id button), you could do:
$("#button").click(function () {
$.ajax({
url: "YourController/GetData",
type: "get",
data: $("form").serialize(), //if you need to post Model data, use this
success: function (result) {
$("#partial").html(result);
}
});
})
Then your action would look something like:
public ActionResult GetData(YourModel model) //that's if you need the model
{
//do whatever
return View(model);
}
Actually, if your Partial has a child action method, you can post (or even use an anchor link) directly to the child action and get an Ajax-like affect. We do this in several Views.
The syntax is
#Html.Action("MyPartial")
The Child Action is
public ActionResult MyPartial()
{
return PartialView(Model);
}
If your form posts to the child action
#using (Html.BeginForm("MyPartial"))
{
...
}
The Partial View will be updated with the partial view returned from the child action.
Jquery is still a legitimate way to update a partial. But technically, the answer to your question is YES.
As normal what I find when looking for things like this is people give too limited information so I will attempt to help here. The key is to set up a div with an ID you can append the return html to. Also when hitting your controller make sure it returns the partial. There are some potential problems with this method but on a good day it should work.
<div id="CategoryList" class="widget">
#{
Html.RenderPartial("WidgetCategories.cshtml");
}
</div>
function DeleteCategory(CategoryID) {
$.get('/Dashboard/DeleteWidgetCategory?CategoryID=' + CategoryID,
function (data) {
if (data == "No") {
alert('The Category has report widgets assigned to it and cannot be deleted.');
}
else {
$('#CategoryList').html(data);
}
}
);
}
[HttpGet("DeleteWidgetCategory")]
[HttpPost("DeleteWidgetCategory")]
public IActionResult DeleteWidgetCategory(string CategoryID)
{
string Deleted = CategoryModel.DeleteCategory(CategoryID);
if (Deleted == "Yes")
{
return PartialView("WidgetCategories");
}
else
{
return this.Json("No");
}
}
I would use the Ajax Form helper for such scenarios using a partial view and #html.RenderPartial("partialName")
partial helpers
In your Main View
<div id=SearchResult>
#Html.Partial("_NameOfPartialView", Model)
</div>
<input type="button" id="btnSubmit" value="Submit">
In your Javascript file
$('#btnSubmit').click(function () {
GetData(Id);
});
function GetData(Id){
$.ajax({
url: "/Home/GetEmployee/",
type: "get",
data: { Id:Id },
success: function (result) {
$('#SearchResult').html(result);
}
});
}
In your Home Controller
public ActionResult GetEmployee(int Id)
{
var employee= context.Employee.Where(x=> x.EmployeeId == Id)
return this.PartialView("_NameOfPartialView", employee);
}
Im developing an MVC project and im using Ajax for displaying a list of shifts.
Here's my parent page, shifts.chtml:
#model UI.ViewModels.ViewModelShiftList
<h2>Shifts</h2>
#Ajax.ActionLink("View All Shifts", "AllShifts", "Shifts",
new AjaxOptions
{
UpdateTargetId="searchResults",
HttpMethod="GET", //default
InsertionMode= InsertionMode.Replace, //replace
LoadingElementId="progress"
})
<div id="searchResults">
#Html.RenderPartial("_ShiftList",model)
</div>
heres the controller action for the above page:
public ActionResult Shifts()
{
ViewModelShiftList viewModel = new ViewModelShiftList
{
Shifts = _shiftService.GetShifts().ToList()
};
return View(viewModel);
}
Should I not be able to send the viewmodel produced here into the partial view? Or do I have to create another action for the partial view? If so, what is the correct way to send an action to the controller of a partialview?
The error im gettin is at this point:
#Html.RenderPartial("_ShiftList",model)
// cannot impilicty convert type void to object
This was a simple fix...I needed to add curly brackets like so..
#{Html.RenderPartial("_shiftlist", Model);}
Suppose I have an action that returns an rendered asp.net mvc control and send it as a response for AJAX request.
I want to have the response of that action during the whole page is rendering in a view.
public class Controller
{
....
public ActionResult AjaxAction(string parameter)
{
return PartialView("~/Views/Controls/Control.ascx",parameter);
}
}
now in view that renders the whole page I want something like:
<%var par = "1";%>
<%= AjaxAction(par) %>
Depending on what you want to achieve partial requests may work for you. This is typically useful where your control is some form of 'widget'.
I would use the jQuery load function, fired when the document is ready, and load the partial view into a div.
$(function() {
$('#partialResult').load( '<%= Url.Action( "AjaxAction", "Controller", new { parameter = "1" } ) %>' );
}
<div id="partialResult">
</div>