MVC 3 Partial View and what I need to send to it? - asp.net-mvc-3

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.

Related

Regarding loading of partial view in mvc

i am new in mvc. now learning. i was searching various technique to load partial view in mvc and i got good one in stackoverflow. here it is.
If you want to load the partial view directly inside the main view you could use the Html.Action helper:
#Html.Action("Load", "Home")
or if you don't want to go through the Load action use the HtmlPartial hepler:
#Html.Partial("_LoadView")
If you want to use Ajax.ActionLink, replace your Html.ActionLink with:
#Ajax.ActionLink(
"load partial view",
"Load",
"Home",
new AjaxOptions { UpdateTargetId = "result" }
)
and of course you need to include a holder in your page where the partial will be displayed:
<div id="result"></div>
Also don't forget to include:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
in your main view in order to enable Ajax.* helpers. And make sure that unobtrusive javascript is enabled in your web.config (it should be by default):
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
after going through the above code one confusion occur. help require. my confusion as below.
#Html.Action("Load", "Home")
#Html.Partial("_LoadView")
i know the use of #Html.Partial("_LoadView") but do not understand how #Html.Action("Load", "Home") will work ?
can anyone show me couple of example to show the various usage of
#Html.Action("Load", "Home")
and how it is different from #Html.Partial("_LoadView")
thanks
Html.Partial
Renders the partial view as an HTML-encoded string.
This method result can be stored in a variable, since it returns string type value.
Simple to use and no need to create any action.
Partial method is useful used when the displaying data in the partial view is already in the corresponding view model.For example : In a blog to show comments of an article, we would like to use RenderPartial method since an article information with comments are already populated in the view model.
#Html.Partial("_Comments")
Html.Action
Renders the partial view as an HtmlString .
For this method, we need to create a child action for the rendering the partial view.
This method result can be stored in a variable, since it returns string type value.
Action method is useful when the displaying data in the partial view is independent from corresponding view model.For example : In a blog to show category list on each and every page, we would like to use Action method since the list of category is populated by the different model.
#{Html.Action("Category","Home");}
#Html.Action("Load", "Home")
Will execute the "Load" ActionResult in your "HomeController".
This Action may return any of these (ref: MSDN):
ContentResult
EmptyResult
FileResult
HttpUnauthorizedResult
JavaScriptResult
JsonResult
RedirectResult
RedirectToRouteResult
ViewResultBase
While
#Html.Partial("_LoadView")
Will insert your partial view "_LoadView" into your current view.
If you're familiar with web forms, think of your partial views as .ascx (user controls).
Edit:
Example of usage of #Html.Action():
Say you have this view:
<p>Here is my name: #Html.Action("Name")</p>
And this is my controller (As you see, I use the overload of Html.Action() that implicit uses the controller you're routed to):
public class FooController : Controller
{
//
// GET: /Foo/
public ActionResult Index()
{
return View();
}
// GET: /Foo/Name
public ActionResult Name()
{
return Content("Annish");
}
}

EditorFor parameters in Action MVC3

Having a bit of trouble figuring something out.
I've got an Action:
public ActionResult FareTypeSelector(SearchTypes searchType, SearchSource searchSource)
{
IFareTypeOptionsRepository fareTypeOptionRespoitory = new FareTypeOptionsRepository();
FareTypeOptions fareTypeOptions = fareTypeOptionRespoitory.GetFareTypeOptions(searchSource, searchType, _authentication.UserLoggedIn.CallCentreUser, _authentication.UserLoggedIn.AgencyProfile.BranchCode);
return View();
}
I've created an 'Editor', i.e. a file in EditorTemplates called FareTypeSelector.cshtml.
I want to bind my editor to a property of the model of the page that contains the editor. But I also want to pass some parameters into my action, i.e. (SearchTypes searchType, SearchSource searchSource). The idea being that the data displayed in the editor is based on this information passed in. Now I can't quite figure out if:
Is this possible?
whats the markup needed in the main view to render
this, pass the parameters and bind the resulting selected value into the main model?
Ta in advance
EditorTemplates are used for Data items from your model, not Action methods. They're using only in your view to render a specific model (or member of a model)

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 POST data and the Id field

I have a strongly typed razor view for a model in my MVC 3 project. Basically its for editing the model.
The model contains an Id field for the database key and some other string fields (Its a viewModel and all but thats not the point of the question).
In the view I just have a form and a submit button and nothing else. When the View is posted to the controller the model in the controller has all fields empty EXCEPT for the Id field which seems to have been auto-magically filled up.
How and where does the Id field gets populated in the model without there being a corresponding 'input' element for it in the view.
This is probably a dumb question but I would appreciate even just a link to what I should read up on. Thanks.
I bet it comes from the url as route parameter.
For example you have the following controller:
public class HomeController: Controller
{
public ActionResult Index(int id)
{
vqr model = GetModel(id);
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// the model.Id property will be automatically populated here
// because the request was POST /home/index/123
...
}
}
and the following view:
#model MyViewModel
#using (Html.BeginForm())
{
<button type="submit">OK</button>
}
Now you navigate to GET /home/index/123 and you get the following markup:
<form action="/home/index/123" method="post">
<button type="submit">OK</button>
</form>
Notice the action attribute of the form? That's where the id comes from. Basically the Html.BeginForm() helper uses the current url when generating the action attribute, and since the current url is /home/index/123 it is what gets used.
And because if you have left the default routes in your Global.asax, the {id} route token is used at the end of the url, the default model binder successfully binds it to the Id property of your view model.
You are probably hitting a URL similar to the following: /MyObject/Edit/15
This is then returning the page that you have your blank form on.
What happens next is you have an HTML.BeginForm() which is posting BACK to /MyObject/Edit/15
Now because of the post back having the same format your routing rules are picking up the '15' and binding it back to your id.
Have you added the ID field as a hidden field?
e.g.
#Html.HiddenFor(x=> x.ID)

Wizard in ASP.NET MVC3 and Multiple HttpPost

I am using the Wizard control described in http://afana.me/post/create-wizard-in-aspnet-mvc-3.aspx
It works great, but I need to have Multiple HttpPost within the same Controller. In my scenario, I need to add to a collection before moving to next step. In the partial view for that step. I have following set up:
#using (Html.BeginForm("AddJobExperience", "Candidate"))
{
<input type="submit" value="Add Experience" />
}
When I press the Add Experience input, it is routed to the
[HttpPost, ActionName("Index")]
public ActionResult Index(CandidateViewModel viewModel)
{
}
instead of
[HttpPost, ActionName("AddJobExperience")]
public ActionResult AddJobExperience(CandidateViewModel col)
{
}
what am I doing wrong?
It sounds like you need to break up your CandidateViewModel into separate ViewModels and your big Wizard View into separate Views so that there is one per action for each step of the wizard.
Step one they add the job experience, so have a view, viewmodel and an action for that, Step two they do whatever else and you have a separate view, viewmodel and action for that as well. etc, etc
Breaking up your CandidateViewModel into separate ViewModels will mean that you can just focus on the data required for that step, and can add the validation, then when they click submit, it posts the data to the next step.
Then, when you want to improve the UI behaviour, add some AJAX, and maybe use something like JQuery UI Tabs to make it behave more like a wizard in a desktop app.
It sounds like you still have nested forms. Don't do this, it is not valid HTML.
You have 2 options here, depending on what you are trying to achieve. If you want to post your job experiences separately one at a time, then put them in their own #using(Html.BeginForms, but don't nest them in an outer form. When a user clicks the Add Experience button, do your work on that one experience and then return a new view to the user.
If you want to post all of the job experiences at the same time, then wrap all of them in a single #using(Html.BeginForm and do not put #using(Html.BeginForm in your partial views. See another question I answered here for more info on how to post a collection of items in a single HTTP POST.
The 2nd method is what it sounds like you are trying to achieve, and for this, you should probably use AJAX to add multiple job experiences to your collection without doing a full postback. You can then do 1 HTTP POST to submit all job experiences in the collection to your wizard controller. It's not very difficult to implement a feature like this:
Given I can see the Add Experience button
When I click the Add Experience button
Then I should see a new experience partial view with input fields
And I should enter data in these fields
When I click the Add Experience button a second time
Then I should see another new experience partial view with input fields
And I should enter data in these fields
When I click the Add Experience button a third time
Then I should see a third new experience partial view with input fields
And I should enter data in these fields
When I click the Next button in the wizard
Then my controller will receive data for all 3 experiences I submitted in a single form
you need to use ActionMethodSelectorAttribute or ActionNameSelectorAttribute which allow to add new attribute on action to call different action on respective of button click
In View:
#using (Html.BeginForm())
{
<input type="submit" value="Add Experience" name="AddExperience" />
<input type="submit" value="Add Experience" name="AddJobExperience" />
}
add new class FormValueRequiredAttribute in application which extend ActionMethodSelectorAttribute class to check on which button is clicked
//controller/FormValueRequiredAttribute.cs
public class FormValueRequiredAttribute : ActionMethodSelectorAttribute
{
public string ButtonName { get; set; }
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
var req = controllerContext.RequestContext.HttpContext.Request;
return !string.IsNullOrEmpty(req.Form[this.ButtonName]);
}
}
then you should add this attribute on action to call corresponding action
In Controller
[HttpPost]
[FormValueRequired(ButtonName = "AddExperience")]
public ActionResult Index(CandidateViewModel viewModel)
{
return View();
}
[HttpPost]
[ActionName("Index")]
[FormValueRequired(ButtonName = "AddJobExperience")]
public ActionResult AddJobExperience_Index(CandidateViewModel viewModel)
{
return View();
}
Note if your Html.BeginForm method in Index.cshtml then you don't need specify ActionName attribute on Index Action, now AddJobExperience_Index act same as Index Action.

Resources