mvc3 calling PartialViews inside ActionResult to put inside DIVs - asp.net-mvc-3

Quick Recap:I have a car website and I have a simple ActionResult with authorization each user that has access to that Controller will have 1 Make of car either a BMW,Honda,Ford or Kia, so that as soon as they login they see the make of car's automatically. I already have the PartialView set but my question is how can I from the ActionResult call the PartialView and fit it inside a DIV within the View?
[Authorize]
public ActionResult Mycars()
{
// How can I return a PartialView here and put it inside a DIV like
// the partialview is called "Mymakes" and its a PartialViewResult
// I just can't seem to put it inside a DIV from here
return View();
}
As said the PartialViewResult works perfectly I have tested it using Ajax.BeginForm
now just trying to render it automatically in the ActionResult any tips would be great !!

in your main view (Mycars), use #Html.Action()
you will create the corresponding Action in your controller (you can set the attribute [ChildActionOnly], and it can be of type PartialViewResult
You will then create the (partial) View corresponding to that PartialViewResult, and... that's it.

Related

How to Access PartialView Result in Master Page in mvc3 using razor

I have a method in controller like this
public PartialViewResult CabinSearch()
{
return PartialView();
}
and I have created a view to this method.
I need to access this partial view to master page
In Razor, the #Html.Partial(viewName) helper will render the named partial view inline in the view. There are other invocations of that to pass a model object to the partial view if it is required.
If you need to invoke the controller method to perform some calculation or database access (as you imply) you can instead use #Html.Action(actionName, controllerName) or some variant of that - where CabinSearch is the action name in your case. This will invoke the controller, which will do whatever it does (model preparation) and then render the partial view, which will then be inlined into the page.

How can we include a form in _layout?

I currently have a _layout.cshtml used by every page of my website.
I need to put a form on each page displayed as a popin.
So, i created a new PartialView (the content of my form) with its corresponding ViewModel and called it in _layout.cshtml.
However, i have a model conflict between ViewModels of pages using the layout and the ViewModel used by the new form (since we can't have directly two models for the same view).
The model item passed into the dictionary is of type 'XXX', but this
dictionary requires a model item of type 'YYY'.
How can we include a form in _layout without this conflict ?
The following has worked for me with a sidebar on every page.
Create a controller for your partial view
In that controller, create a method for the view you want to return, and be sure to use the [ChildActionOnly] filter
public class PartialController : Controller
{
[ChildActionOnly]
public PartialViewResult Alerts()
{
return PartialView("Alerts", messages);
}
}
In your _layout view, you'll have the following:
#Html.Action("Alerts", "Partial")
(instead of #Html.RenderPartial or #Html.Partial)
It sounds like you already have what you need for the view.
I have not used this with a form, but it should work similarly. Hope this helps.

MVC 3 Partial View and what I need to send to it?

I am wondering about a couple variations of forms and partial forms. The submit is on the parent page and I have varied what I pass to the partial view. I have a parent view with a related HomeViewModel (which has public properties Name and public Person Employee {get;set;}
1.) Scenario 1: The main view has something like the following
#model MasterDetailSample.Models.HomeViewModel
#using (Html.BeginForm()) {
<div>
#{Html.RenderPartial("_PersonView", #Model);}
</div>
<input type="submit" value="Save" />
}
In this scenario I am passing to the partial view _PersonView the entire HomeViewModel. Within _PersonView partial view I have to reference a property of the HomeViewModel i.e. Person object via #model.Employee.Name (in this scenario the submit is on the parent form (not within the partial view))
When I hit submit on the form (POST) in the controller i have to access the property of Employee "Name" via the following model.Employee.Name
This seems to work however notice the following variation scenario 2 (where I only pass to the partial the Employee object)
2.) Scenario 2
In this scenario I only want to send the Employee object to the partial view. Again the begin form and submit is on the parent form.
So from the parent form i have
#{Html.RenderPartial("_MasterView", #Model.Employee);}
and so within the partial view i reference the Name property of the Person object via #Employee.Name Now when I submit the form within the controller the Employee object is not available from the auto model binder. I can access the properties via formcollection but not from the model parameter
i.e.
[HttpPost]
public ActionResult Index(ModelViewModel model) {
**//model.Employee is null!**
return View();
}
Why? (is model.Employee null) I would like my partial view to only accept an object of type Person however after submitting from the parent page, the Employee property is null. On the partial view I am using the following on the #model line
#model MasterDetailSample.Models.Person
I would like the partial to only need a Person object to be sent to it, but I would like the submit on the main form. If i do it this way I can re-use the partial view in a few situations however IF i must send HomeViewModel i have significantly limited how I can use this partial view. So, again, I only want to use Person as the model with the partial view but I need to be able to access the properties when submitted from the parent view.
Can this be done? If yes how?
thx
You have a couple of options:
1) One I recommend -> Dont use partial views, instead use EditorFor and create an editor template for Person. With partial views the context is whatever model you pass into the view, this is why your example (1) works and (2) not. However with editor templates the parent context is taken into consideration with the html helpers and will generate the correct input names. Have a look at Darin Dimitrov's answer to a similar question.
2) Use your second example as is, but change the post action to look something like this:
[HttpPost]
public ActionResult Index(ModelViewModel model) {
TryUpdateModel(model.Employee);
**//model.Employee should now be filled!**
return View();
}
3) Use custom html helpers that accepts prefix for input, see this answer I posted a while back for example code. You could then use this inside your partial view.

Refreshing parent view when a partial view's form is submitted

I'm looking into using partial views in MVC3 using Razor, and I get my partial view to render and it works fine.
What I'd like to do, though, is refresh the parent view when the partial view is submitted.
Code in my parent view to render partial view
<div id="mydiv">
#{ Html.RenderAction("Add", "Request"); }
</div>
Action for parent view is simple,
public ActionResult Index()
{
List<obj> reqs = //some query
return View(reqs);
}
In my partial view's get action I have:
public ActionResult Add()
{
AddRequestViewModel vm = new AddRequestViewModel();
//set some stuff on the VM here
return PartialView(vm);
}
In the post action called by the partial view, if modelstate isn't valid, return PartialView(vm)
If it is valid, I'd like the parent and partial views to refresh.
I tried RedirectToAction, but this can't be called in an action called by a partial, apparently, and I tried return Index();, but this causes an issue with the code used to render the partial view,
Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List'1[DatRequests.Models.ReqRequest]', but this dictionary requires a model item of type 'DatRequests.ViewModels.AddRequestViewModel'.
Any suggestions on how to do this would be appreciated. The purpose of the page is to show a list of elements, and the partial contains a form to add a new element to the list.
Edit: The partial's model is different, as it contains data for selection, which is from a db, which is why I tried RenderAction, but I'm not sure if there are other ways of doing this.
When the partial view is submitted normally you submit it to some controller action. You could either submit it using a normal request or an AJAX request. If you use a normal request you could perform a standard redirect to the Index inside the POST controller action that will handle the form submission. If you use AJAX, you could return a JSON result pointing to the url that you want to redirect:
[HttpPost]
public ActionResult Foo(MyViewModel model)
{
if (!ModelState.IsValid)
{
return PartialView(model);
}
return Json(new { url = Url.Action("Index") });
}
and inside your AJAX success callback:
success: function(result) {
if (result.url) {
// we have a success
window.location.href = result.url;
} else {
// invalid modelstate => refresh the partial
$('#mydiv').html(result);
}
}
Probably RenderAction should not be used this way.
When using Html.RenderAction, a new/seperate request would be sent to the server. And you got another chance to load some data from db or somewhere else to display to the client. Also, you could apply OutputCache to this action. this is usually the way doing global cache.
Here you are doing a POST to the server. Either directly put a element here or using a partial view to do the Post. And in the corresponding action, do a RedirectToAction.
Do it with ajax or not isn't the point. my opinion is more about the right way using RenderAction

Calling another Controller post method

I am using ASP.NET MVC 3 for my website.
I have created a partial view that has "Previous, Next and Save" buttons. I am calling this partial view on my master page.
My requirement is that on what ever View I am I must be able to call different Save methods in different controllers by passing respective Model data to controller actions.
Example
I have 4 step data input, I have a different controller for each step.
If i am on step 1 and i click Save the form Values should go to Step1Controller's action method,
If I am on step 2 then post should call Step2Controller
Something like this this:
public ActionResult Save(GenericModel model)
{
//use reflection to find out model type
//call appropriate controller action with model
return RedirectToAction("Create", new { Controller = "Conference", Action = "Create" });
}
This save method will be called for Save button on the Master page. How can I achieve this?
Are the forms on separate actions on the controllers?
If so, just set the form action on each page to point to the relevant controller. So form 1 is
<form method="post" action="/step1controller/action">
Form 2 is:
<form method="post" action="/step2controller/action">
Does that solve your problem?
I would create a private method in the controller and call in every part of the first steps.
private bool Save(GenericModel model)
{
......
}
[HttpPost]
public bool SaveStep1(GenericModel model)
{
this.Save(model);
}
[HttpPost]
public bool SaveStep2(GenericModel model)
{
this.Save(model);
}

Resources