Passing a selected value from a partial view to the main view's viewmodel - asp.net-mvc-3

As ASP.Net MVC3 newbies we have an issue that would like assistance with. (Questions at the bottom of this thread too.)
First of all I am not sure if the following is the best way to go about this so please let me know if we are heading in the wrong direction. We would like to use partial views to do lookups for dropdown lists. In some cases the lookups will be done in multiple places and also, the data is not part of our viewmodel. The data may be coming from a Database or Web Service in our application. Some of the data is loaded at startup and some is based upon other values selected in the form.
We are calling a child action from our main view and returning a partial view with the data we obtained. Once the user selects their choice we are not sure how to store the selected item code in our main view model.
In our main form we call to an action:
#model Apps.Model.ViewModels.AVMApplicationInfo
...
<div class="editor-label">
#Html.LabelFor(m => m.VMResidencyWTCS.DisplayState)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.VMResidencyWTCS.DisplayState)
#Html.DropDownListFor(m => m.VMResidencyWTCS.DisplayState, Apps.Model.Helpers.ResidencyStates.StateList)
#Html.ValidationMessageFor(m => m.VMResidencyWTCS.DisplayState)
</div>
#Html.Action("DisplayCounties", "PersonalInfo")
...
In the PersonalInfo controller:
[ChildActionOnly]
public ActionResult DisplayCounties()
{
IList<County> countiesDB = _db.Counties
.OrderBy(r => r.CountyDescr)
.Where(r => r.State == "WI"
&& r.Country == "USA")
.ToList();
//Create an instance of the county partial view model
VMCounty countyView = new VMCounty();
//Assign the available counties to the view model
countyView.AvailableCounties = new SelectList(countiesDB, "CountyCd", "CountyDescr");
return PartialView("_DisplayCounties", countyView);
}
In the _DisplayCounties partial view:
#model Apps.Model.ViewModels.VMCounty
<div class="editor-label">
#Html.LabelFor(m => m.CountyDescr)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.SelectedCountyCd, Model.AvailableCounties)
</div>
How do I assign the SelectedCountyCd to a field in the main form view model (Apps.Model.ViewModels.AVMApplicationInfo )? Are there any issues of when the child action/partial view is called; i.e., is it loaded at start up and can this method be used to include a user choice as a filter for the lookup? If so, how could the value be passed to the child controller; viewbag?

You could pass it as parameter to the child action:
#model Apps.Model.ViewModels.AVMApplicationInfo
...
#Html.Action("DisplayCounties", "PersonalInfo", new {
selectedCountyCd = Model.CountyCd // or whatever the property is called
})
and then have the child action take this value as parameter:
[ChildActionOnly]
public ActionResult DisplayCounties(string selectedCountyCd)
{
IList<County> countiesDB = _db.Counties
.OrderBy(r => r.CountyDescr)
.Where(r => r.State == "WI"
&& r.Country == "USA")
.ToList();
//Create an instance of the county partial view model
VMCounty countyView = new VMCounty();
//Assign the available counties to the view model
countyView.AvailableCounties = new SelectList(countiesDB, "CountyCd", "CountyDescr");
// assign the selected value to the one passed as parameter from the main view
countyView.SelectedCountyCd = selectedCountyCd;
return PartialView("_DisplayCounties", countyView);
}

Related

ASP.NET MVC3 passing data between primary view and a search view via Ajax link

I have just started learning ASP.NET MVC3.
I have the following scenario. In a create view for a certain model the user can lookup code/description by clicking on a link (rendered with Html.ActionLink helpers). The lookup values are retrieved from lookup tables in a database and presented in a separate view. The two views are handled by two different controllers. When the user selects a lookup value in the latter view that value (code+description) should be copied back to the create view.
How can data be passed between the two views? Is this not possible due to the stateless nature of Http requests?
I tried that with an Ajax link, but it didn't worked out.
code snippet Create view:
<fieldset>
<legend>Z-Info</legend>
<div class="editor-label">
#Html.LabelFor(model => model.ZZL_U_CODE)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ZZL_U_CODE)
#Html.ValidationMessageFor(model => model.ZZL_U_CODE)
</div>
<div class="editor-label">
#Ajax.ActionLink("Land code test", "Index", "Domein", new {name = "lan" },
new AjaxOptions {
HttpMethod = "Get",
Url = Url.Action("Index", "Domein", new {name = "lan" }),
OnBegin = "OnBegin",
OnSuccess = "InsertCodeNaam",
OnFailure = "OnFailure",
OnComplete = "OnComplete"
})
</div>
When the user select a code/description the following Select action is called which returns Json data back.
Select action:
public class DomeinController : Controller
{
private ZZLEntities db = new ZZLEntities();
//
// GET: /Domein/
public ViewResult Index(string name)
{
DomeinViewModel model = DomeinRepositry.GetAll(name);
return View(model);
}
GET: /Domein/Select/5
public JsonResult Select(int id, string naam)
{
return Json(new DomCodeNaam { codeValue = id, naamValue = naam }, JsonRequestBehavior.AllowGet);
}
Are there other solutions possible? Can partial views be an option?
Well you have two options:
Just post back lookup values and then internally redirect to the
first ("create") view, but this time passing (internally) the values
chosen by user so the view can be rendered with chosen values. Maybe
not fancy but very easy to implement. You will loose data that user have already entered into first form though, unless you post it too or you make this a 2 step process.
If you want to use Ajax, you need update appropriate parts of the
form in the first "create" view on the client side, depending on the
actions of user (i.e. what lookup values they have chosen).
I am however a bit confused with what you exactly mean by "separate view"

MVC3 Dropdown selection based on other Drop down value

Hi there im working on MVC3 and have problem with dropdown selection:
I have a table call CSystem and it hold value System1 and System2
another table call SystemModule hold System1Module and System2Module
But at dropdown selection at job view when System1 is selected the SystemModule still appear all value. Please help.
Controller:
public ActionResult Create()
{
ViewBag.CSystemID = new SelectList(db.CSystems, "CSystemID", "SystemName");
ViewBag.SystemModuleID = new SelectList(db.SystemModules.Where(x => x.CSystemID == CSystems.CSystemID), "SystemModuleID", "ModuleName");
return View();
}
View:
<div class="editor-label">
#Html.LabelFor(model => model.SystemModuleID, "SystemModule")
</div>
<div class="editor-field">
#Html.DropDownList("SystemModuleID", String.Empty)
#Html.ValidationMessageFor(model => model.SystemModuleID)
</div>
It appears you aren't passing in a model? I don't understand exactly what you are asking, but that is one glaring thing I can see in your code... hope this helps :\

Dropdown list filled from repository

I have an MVC3 drop down list that come from this code on the controller.
private SelectList progCodesList = new SelectList(new[] { "Description", "Requirements", "Development", "Testing", "Documentation" });
How can I fill the fields from a repository, to build the drop down dynamically?
Thanks.
Assuming you have the progCodes in a database table, with progCode having the text, and progCodeId with a unique id, then you can read the table into a list of SelectListItem as follows:
private DbContext _db = new DbContext();
var progCodesList = _db.progCodes.Select(x => new SelectListIem()
{
Text = x.progCode,
value = x.progCodeId
}).ToList();
You can then pass this List<SelectListItem> to your view either in a strongly-typed model, or using the ViewBag.
You need to pass the progCodesList to the ViewBag in your controller method using something like:
ViewBag.ProgCodeId = progCodesList;
Then in your view, you need to fill the drop down like this:
<div class="editor-label">
#Html.LabelFor(model => model.ProgCodeId, "ProgCode")
</div>
<div class="editor-field">
#Html.DropDownList("ProgCodeId", String.Empty)
#Html.ValidationMessageFor(model => model.ProgCodeId)
</div>

ASP.NET MVC 3 #Html.DropDownListFor ignoring selectedValue

In my asp.net MVC 3 project I would like to create a contact that's related to a company.
You can either directly create a contact OR go via the company details view and add a new contact passing the companyId to set that company already in the dropdown on the contact create form.
The problem is that I can 't get the passed company as default in my dropdown.
Global.asax
routes.MapRoute("contactCreate", "contact/toevoegen/{companyid}", new { action = "ContactCreate", controller = "Backend", companyid = UrlParameter.Optional });
Controller method
public ActionResult ContactCreate(int? companyid)
{
Contact contact = new Contact();
ViewBag.StatusList = srep.getContactStatusses();
ViewBag.CompanyId = companyid;
return View(contact);
}
View
#model xxx.Models.Contact
...
<div class="editor-label">
#Html.LabelFor(model => model.bedrijf_id)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.bedrijf_id, new SelectList(ViewBag.Bedrijven, "bedrijf_id", "bedrijf_naam",ViewBag.CompanyId), "--Kies bedrijf--")
#ViewBag.CompanyId
#Html.ValidationMessageFor(model => model.bedrijf_id)
</div>
...
#ViewBag.CompanyId has a value.
Any idea why it's not setting the selected value?
When doing a "DropDownListFor" it will try to match up the value passed in from the model for the selected value. So in your example it will use "bedrijf_id" as the selected value. It looks like you want the selected value to be from something outside of your model.
From the comments I think what you want is just a DropDownList as follows:
#Html.DropDownList("DropDownList", new SelectList((ViewBag.Bedrijven, "bedrijf_id", "bedrijf_naam", ViewBag.CompanyId), "--Kies bedrijf--")
Hope this helps.

ViewModel has no properties set in Model using HttpPost Create method

I have a simple MVC3 app with an EF4 Model
Log
.Name
.CreatedDate
.LogTypeId
LogTypes
.Id
.Description
and a ViewModel
LogViewModel
Log MyLog
List<SelectListItem> Options
LogViewModel(){
Log = new Log();
}
This displays in my view correctly and I can edit/update the values, display the drop down list and set the name to "MyTestValue".
However, in my controller's HttpPost Create method the properties for logVm.Log are not set?
[HttpPost]
public ActionResult Create(LogViewModel logVm){
logVm.Log.Name == "MyTestvalue"; //false - in fact its null
}
What am I doing wrong?
That's probably because in your edit form you don't have corresponding values. So if yuor view is strongly typed to LogViewModel the form input names must be appropriately named:
#model LogViewModel
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(x => x.Log.Name)
#Html.EditorFor(x => x.Log.Name)
</div>
<div>
#Html.LabelFor(x => x.Log.SomeOtherProperty)
#Html.EditorFor(x => x.Log.SomeOtherProperty)
</div>
...
<input type="submit" value="OK" />
}
sop that when the form is submitted the POSTed values look like this:
Log.Name=foo&Log.SomeOtherProperty=bar
Now the default model binder will be able to successfully bind your view model. Also make sure that the properties you are trying to assign are public and that have a setter.
The controller method should have a property named model
[HttpPost]
public ActionResult Create(LogViewModel **model**){
**model**.Log.Name == "MyTestvalue"; //true }

Resources