Is there any way i can know that partial view is called from which main view?
I have one partial view being called from two main views with different data.
MainIndex1.cshtml
#Html.Partial("~/Views/Shared/_partialView.cshtml", Model)
MainIdex2.cshtml
#Html.Partial("~/Views/Shared/_partialView.cshtml", Model)
so, in _partialView how i can know that it is called from which main view?
If you want to see which controller and action is participating to call this partial view. So if you want to get the parent context inside this child action you could do this:
public ActionResult Menu()
{
var rd = ControllerContext.ParentActionViewContext.RouteData;
var currentAction = rd.GetRequiredString("action");
var currentController = rd.GetRequiredString("controller");
...
return View();
}
or you can also use this code to find out the controller and action name for current request.
Controller: #ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
<br />
View: #ViewContext.Controller.ValueProvider.GetValue("action").RawValue
refer following thread on stackoverflow..
Get the parent controller name from partialview action
hope this will help you.
thanks
Related
My Get ActionMethod :
public ActionResult GetData(int id)
{
TestModel testModel = new DataAccess().GetData(id);
return View(testModel);
}
View
#model TestModel
#using (Html.BeginForm("UpdateRequest", "Home", FormMethod.Post))
{
<div>
#Html.Partial("_Information", Model.Information)
</div>
<input type="submit" id="btnSubmit" value="Save" />
}
The data is displayed correctly in the _Information partial view. But when I click on Save button the model passed to Controller is null.
Home Controller method is as follows :
[HttpPost]
public ActionResult UpdateRequest(TestModel testModel)
{
new DataAccess().UpdateData(testModel);
.....
}
But the model received for UpdateRequest is null
Please help to resolve this issue.
Note: The partial view does not contain any additional BeginForm Tags.
If the individual controls of the Partial view are added in the main View the model object is populated.
Have you checked what the form collection has in it when the controller posts back?
I would hazard a guess that the HtmlFieldPrefix is being set which is causing your form controls to have a strange name that doesn't match your POCO.
You can chance the HtmlFieldPrefix in your partial view to match the sub object that you want to set by using:
#ViewData.TemplateInfo.HtmlFieldPrefix = "Your sub object property name here"
HTH
In my MVC controller I have two action methods.
The first one is Index method:
public IActionResult Index()
{
return PopulateViewModel();
}
The "PopulateViewModel" Action Method is used for updating of the view model and then showing these updated values on the Index view.
public IActionResult PopulateViewModel()
{
ViewModel viewModel = new ViewModel()
{
//updating values in the view model
//the values are received when the form in the view is submitted
};
return View("Index", viewModel);
}
The problem that I have is that on my Index view the updated values are not shown immediately after submitting the form in the view. When I submit the form I must then once again refresh the page to see the updated values.
What could be the reason for such behavior and how can I correct that?
You misunderstand the conceptual notion. The index is supposed to represent the initial page state. Other actions within the controller will modify the output by rendering the page with the adjusted model. Or handling server side model binding, but the concept is fundamentally achieving the same result.
Your controller logic should be within the following constraints.
public class SampleController : Controller
{
public IActionResult Index() => new View("...", ...);
public IActionResult SubmitSample(string location)
{
var model = service.GetLabLocations(location);
return View("...", model);
}
}
The index is simulating a GET request, returning the initial page in the required state. The form portion, should POST data, outlined in the SubmitSample portion of the code. This will change the state of the page, but the server will need to render with those changes. So the page will load with the attached model, for you to display.
This would represent Razor more than likely on the server side.
#if(Model != null)
foreach(var sample in Model)
{
// Markup, with the data
}
I have models (POCO entities) like Student, Course, Standard etc. I have corresponding controllers such as StudentController etc. I have a view Index for each model which displays the list of all the corresponding entities in DB. For example, StudentController.Index() returns the /Student/Index view. However, if there are no Student records in the DB, instead of returning the Index view , I redirect to the Empty action method of the Navigation controller, i.e. NavigationController.Empty(), which returns the /Navigation/Empty view. This is done for all model entity classes.
Now, on the empty page, I wish to have a hyperlink to go back to the previous page. So I created an action method called GoBack() in the NavigationController class, in which I redirect to the previous view. But how can I access the information about what the previous page was in this action method? Or is there a better way to do this? I do not want to use the back button.
As far as I'm concerned there are a couple of routes to take here. You could use sessions or the application cache to store a las visited page, and then get that page (by storing a route for instance) in the GoBack() action using a RedirectToAction.
But maybe a nicer and stateless aproach would be to render the hyperlink by having a view model having two properties for last used controller & action. Then you could pass these from the action result calling the /Navigation/Empty action (when there aren't any records).
ViewModel
public class NavigationVM
{
public string LastAction {get;set;}
public string LastController {get;set;}
}
Navigation Controller Action
public ActionResult Empty(string lastAction, string lastController)
{
var vm = new NavigationVM()
{
LastAction = lastAction,
LastController = lastController
}
return View(vm);
}
View
#model = Namespace.NavigationVM
#Html.ActionLink("LinkName", Model.LastAction, Model.LastController)
EDIT
If you then need to find out from where the students controller was called (in your example) you can go about this the same way. I.e.: Render the link to the StudentsController with extra route values.
StudentController:
public ActionResult Index(string lastAction, string lastController)
{
.... // no students
return RedirectToAction("Empty", "Navigation", new RouteValueDictionary(new { lastAction = "Index", lastController= "Student"}));
}
View with hyperlink to students controller (use the action and controller that rendered this view as lastAction and lastController respectively):
#Html.ActionLink("Get students", "Index", "Student", new { lastAction= "Index", lastController = "CallingController" }, null)
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());
});
I'm new to MVC and I wanna render a partial view in a popup within a view, but I wondering how to provide the partial view's model.
<div id="enumsDialog" class="dialog">
#Html.Partial("~/Views/Enumeration/List.cshtml", [it needs a modal here])
</div>
In another words, I want the partial view to deal with its own controller.
How to implement that?
If you are wanting to render a partial view whose action/data comes from a different controller, then you will probably want to use the RenderAction method:
#Html.Action("MyAction", "MyController")
If you are wanting to render a partial view with data from your current viewmodel (without having to make another request of your application), then use the RenderPartial method:
#Html.Partial("NameOfView", Model.WhateverYouArePassing)
The easiest way is this one:
public class EnumerationController : Controller {
// other actions...
public ActionResult List(){
// TODO: var model = retrieve-your-model-here
return PartialView(model);
// using "PartialView" instead of "View" method ensures this action isn't
// responsible from direct requests
// Also you can use "PartialViewResult" class as a return-type instead
// of "ActionResult" in method, like "List2()" method below:
}
public PartialViewResult List2(){
// TODO: var model = retrieve-your-model-here
return PartialView(model);
}
}
and in .cshtml file:
#{Html.RenderAction("List", "Enumeration");}
// or:
#Html.Action("List", "Enumeration")