EditorFor parameters in Action MVC3 - asp.net-mvc-3

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)

Related

Is it possible to send Model data from a View to a Controller that is not the Controller for that View?

I could not find the similar question yet, so I decided to ask it here.
I relatively new to MVC and may have some incorrect wording in my question, and I'm just wondering if that is possible to do it at all?
Usually, we are dealing with ModelViewController coupling and we return the View from a Controller with Models/Json as parameters to the returning View, so we can bind the Model to the View
I'm just wondering if we have a ViewA, ViewB ControllerA,ControllerB and a ModelA, is that possible to have a #Url.Action/Link or Ajax method to send the ModelA from the ViewA to an Action Method of a ControllerB, so, the data stored in the ModelA can be displayed in the ViewB when it is returned from the ControllerB?
I do not have any code yet and just want to know if that is possible and if so, what would be the right approach to achieve something like that?
You could do something like this:
Controller B:
public IActionResult ControllerB(ModelA data)
{
return View(data);
}
View A:
#foreach (var data in Model)
{
<li>#Html.ActionLink(#data.ModelAProperty, "ControllerB", "ControllerBFileName", new { id = data.Sys.Id })</li>
}
View B:
#model YourModel.Models.ModelA
<div>
<h3>#Model.ModelAProperty</h3>
<p>#Model.ModelAOtherProperty</p>
</div>
This should work I believe. I did this with a previous project but it was a slightly different set up, but I believe I have modified it correctly to fit your needs. Basically you are passing the data to the controller with the first view, and then using that controller to pass the data to the next view.

how to pass parameters to controller from view

I need to pass parameters from a view to control in a form. These parameters are for example a string that is not in a textField. The string is "FATHER" and I send this string from the view to the controller when I click on the submit button in the form. Anyone can suggest how I can do it?
add a hidden input field to your form with a value of "FATHER":
<?= form_hidden('name_of_field', 'FATHER') ?>
and in your controller, get the value when the form is submitted:
$value = $this->input->post('name_of_field');
So if this question is about asp.net MVC ... :
Are you using a strongly typed view, do you have a ViewModel? If so, add a property of type string, say StringToHide, to it, set it to "FATHER" and then, in your form, add
#Html.HiddenFor(StringToHide)
Then the information will be passed to the controller, but it is not editable by the user. And if you're not using a viewmodel yet, well, then you should. It's a clean way to compose all your data when passing from views to controllers and vice versa.
Assuming Asp.net MVC
In View
#{ Html.RenderAction("Menu", "", new { parameterFromView= "FATHER" }); }
In Controller
[HttpPost]
public ActionResult Menu(string parameterFromView)
{
// do whatever
}
In jquery call append the text Father to the URL and accept it in controller.
see code below.
$("#submit").click(funtion(){
window.url = "Controller/Action/" + "Father";
});

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");
}
}

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.

Resources