How to use DropdownListFor on Multiple model view - c#

It's been a while since I visited StackOverflow...
So, i've started using ASP.NET MVC4 with Razor, using a Model-first approach to Entity Framework. So far i've liked it , althoug I have had problems remembering certain stuff.
For example, now i'm trying to implement a simple Login form, that includes Username + Password + UserType. However, as I recall from my experiences from MVC3, you cannot pass along two models... unless you use a Tuple.
So, my objective is to create the form via #HTML helpers, but the only one i've been unable to use is the DropdownListFor, that would bring forth the list of User Types and apply them in the form.
#model Tuple<EMS_v1.User, EMS_v1.UserType>
#{
ViewBag.Title = "Log in";
}
<section id="loginForm">
<h2>Use a local account to log in.</h2>
#using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Log in Form</legend>
<ol>
<li>
#Html.Label(" User Name")
#Html.TextBoxFor(m => m.Item1.User_Name)
#Html.ValidationMessageFor(m => m.Item1.User_Name)
</li>
<li>
#Html.Label("Password")
#Html.PasswordFor(m => m.Item1.User_Pass)
#Html.ValidationMessageFor(m => m.Item1.User_Pass)
</li>
<li>
#Html.Label("Portal Access")
>>>>> #Html.DropDownListFor(model => model.Item2.Type_Id, new SelectList(Model.Item2, "Type_Id", "Description"));
</li>
</ol>
<input type="submit" value="Log in" />
</fieldset>
}
</section>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
My Entity Framework Model includes UserType (int Type_Id, String Description) and User (int Id, String User_Name, String User_Pass, UserTypeType_Id), being UserTypeType_Id a Foreign Key that refers back to UserType table.
Is there any way to generate the list or IEnumerable from the UserType table? because I'm sure the code I posted doesn't work properly.

Create a collection in the action method of controller and assign it to some Viewbag property
e.g
ViewBag.UserType = new SelectList();
this collection should be IEnumerable type object.
Now use this ViewBag prorety from view.
e.g.
#Html.DropDownList ("UserType" , "Select User Type")

You really shouldn't be using the Entity Framework entities in your views. Create a viewmodel for example:
public class LoginViewModel
{
public string Username{get;set;}
public string Password{get;set;}
public int UserTypeId{get;set;}
public IEnumerable<UserTypes> UserTypes{get;set;}
}
Then in your dropdown:
#Html.DropDownListFor(m => m.UserTypeId, Model.UserTypes.Select(t => new SelectListItem { Value = t.TypeId.ToString(), Text = t.Description }));

Related

Persisting Collections in ViewModel

I've been struggling for quite some time now with trying to maintain a list of objects when the ViewModel is submitted back to the controller. The ViewModel receives the list of objects just fine, but when the form is submitted back to the controller the list is empty. All of the non-collection properties are available in the controller, so I'm not sure what the issue is. I have already read the guide a few people have referenced from Scott Hanselman here
From what I can see, everyone solves this by building an ActionResult and letting the model binder map the collection to a parameter:
Controller:
[HttpPost]
public ActionResult Submit(List<ConfigurationVariable> variables)
{
}
View:
#for (int i = 0; i < Model.ConfigurationVariables.Count; i++)
{
<div class="row">
<div class="col-xs-4">
<label name="#Model.ConfigurationVariables[i].Name" value="#Model.ConfigurationVariables[i].Name" />
</div>
</div>
<div class="row">
<div class="col-xs-4">
<input type="text" class="form-control" name="#Model.ConfigurationVariables[i].Value" value="#Model.ConfigurationVariables[i].Value" />
</div>
</div>
}
What I really want is to be able to pass my ViewModel back to the controller, including the ConfigurationVariables List:
Controller:
[HttpPost]
public ActionResult Submit(ReportViewModel report) //report.ConfigurationVariables is empty
{
}
View:
#for (int i = 0; i < Model.ConfigurationVariables.Count; i++)
{
<div class="row">
<div class="col-xs-4">
#Html.LabelFor(model => model.ConfigurationVariables[i].Name, new { #class = "form-control" })
</div>
</div>
<div class="row">
<div class="col-xs-4">
#Html.TextBoxFor(model => model.ConfigurationVariables[i].Value, new { #class = "form-control" })
</div>
</div>
}
This will be a complicated form and I can't just put every collection into the ActionResult parameters. Any help would be greatly appreciated
You need to hold the Name property in a hidden input so that it's submitted. Label values are lost.
#Html.HiddenFor(model => model.ConfigurationVariables[i].Name)
Alright, based on your comment you won't be able to utilize mvc's form binding. No worries.
Instead of this controller definition:
public ActionResult Submit(List<ConfigurationVariable> variables)
Use one of these two:
public ActionResult Submit()
public ActionResult Submit(FormCollection submittedForm)
In the first you can access the Request object, you'll need to debug and locate your variable, then you'll need some logic to parse it apart and used the values submitted.
In the second, the form collection will be made up of all the INPUT elements in your form. You will be able to parse through them directly on the object without interference from the other attributes of the Request object.
In both cases you will probably need to use #Html.TextBox, and not TextBoxFor, and you will need to dynamically populate your dropdowns in your view.
I'm not 100% sure about the Request object, but for sure on the FormCollection you will need to create an Input element for each value/collection you want submitted. Including hidden inputs for your textboxes
Your textboxes will need to be SelectListItem collections. those require a key and a value, and when they are submitted you can loop through the collection and check the .Selected attribute.
I would try with FormCollection first, and if that doesn't work fall back to the Request object.
Also note: you are not getting a viewmodel back from the form submission, you will need to rebuild it from the form elements. If you want to post prepopulated data to the view you will need to build a view model and do appropriate parsing on the view to display it.

Partial within a partial null exception

I have a MVC form which is more complex than all of my others, utilising three models.
Company -> Base_IP -> RequestedIP which goes ViewModel -> Partial1 -> Partial2
I am using BeginCollectionItem for this has each model has a property list of the the model down from it. IE - Company has a property called baseIps, the BaseIp class has a property called requestedIps, it is requestedIps that is coming back null, the count is there on page render, but is not on submit.
When submitting to the database in the post Create(), I get nulls on the 'requestedIps' property, why is this?
I've added the offending controller and partial code samples below, not the entire thing as it's massive/redundant - any questions, please let me know.
Controller - [HttpGet]Create()
public ActionResult Create()
{
var cmp = new Company
{
contacts = new List<Contact>
{
new Contact { email = "", name = "", telephone = "" }
}, pa_ipv4s = new List<Pa_Ipv4>
{
new Pa_Ipv4
{
ipType = "Pa_IPv4", registedAddress = false, existingNotes = "", numberOfAddresses = 0, returnedAddressSpace = false, additionalInformation = "",
requestedIps = new List<IpAllocation>
{
new IpAllocation { allocationType = "Requested", cidr = "", mask = "", subnet = "" }
}
}
}
};
return View(cmp);
}
Controller - [HttpPost]Create()
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Company cmp) // does not contain properties assigned/added to in view render
{
if (ModelState.IsValid)
{
db.companys.Add(cmp);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(cmp);
}
Create View
#model Company
#using (Html.BeginForm())
{
<div id="editorRowsAsn">
#foreach (var ip in Model.pa_ipv4s)
{
#Html.Partial("Pa_IPv4View", ip)
}
</div>
<br />
<div data-role="main" class="ui-content">
<div data-role="controlgroup" data-type="horizontal">
<input type="submit" class="ui-btn" value="Create" />
</div>
</div>
}
Pa_Ipv4 View
#model Pa_Ipv4
#using (Html.BeginCollectionItem("pa_ipv4s"))
{
#Html.AntiForgeryToken()
<div id="editorRowsRIpM">
#foreach (var item in Model.requestedIps)
{
#Html.Partial("RequestedIpView", item)
}
</div>
#Html.ActionLink("Add", "RequestedManager", null, new { id = "addItemRIpM", #class = "button" }
}
RequestedIpView
#model IpAllocation
<div class="editorRow">
#using (Html.BeginCollectionItem("requestedIps"))
{
<div class="ui-grid-c ui-responsive">
<div class="ui-block-a">
<span>
#Html.TextBoxFor(m => m.subnet, new { #class = "checkFiller" })
</span>
</div>
<div class="ui-block-b">
<span>
#Html.TextBoxFor(m => m.cidr, new { #class = "checkFiller" })
</span>
</div>
<div class="ui-block-c">
<span>
#Html.TextBoxFor(m => m.mask, new { #class = "checkFiller" })
<span class="dltBtn">
<img src="~/Images/DeleteRed.png" style="width: 15px; height: 15px;" />
</span>
</span>
</div>
</div>
}
</div>
You first (outer) partial will be generating correct name attributes that relate to your model (your code does not show any controls in the Pa_Ipv4.cshtml view but I assume you do have some), for example
<input name="pa_ipv4s[xxx-xxx].someProperty ...>
however the inner partial will not because #using (Html.BeginCollectionItem("requestedIps")) will generate
<input name="requestedIps[xxx-xxx].subnet ...>
<input name="requestedIps[xxx-xxx].cidr ...>
where they should be
<input name="pa_ipv4s[xxx-xxx].requestedIps[yyy-yyy].subnet ...>
<input name="pa_ipv4s[xxx-xxx].requestedIps[yyy-yyy].cidr ...>
Normally you can pass the prefix to the partial using additional view data (refer this answer for an example), but unfortunately, you do not have access to the Guid generated by the BeginCollectionItem helper so its not possible to correctly prefix the name attribute.
The articles here and here discuss creating your own helper for handling nested collections.
Other options include using nested for loops and including hidden inputs for the collection indexer which will allow you to delete items from the collection and still be able to bind to your model when you submit the form.
for (int i = 0; i < Model.pa_ipv4s.Count; i++)
{
for(int j = 0; j < Model.pa_ipv4s[i].requestedIps.Count; j++)
{
var name = String.Format("pa_ipv4s[{0}].requestedIps.Index", i);
#Html.TextBoxFor(m => m.pa_ipv4s[i].requestedIps[j].subnet)
#Html.TextBoxFor(m => m.pa_ipv4s[i].requestedIps[j].cidr)
...
<input type="hidden" name="#name" value="#j" />
}
}
However if you also need to dynamically add new items you would need to use javascript to generate the html (refer examples here and here)
If you look at your final markup you will probably have inputs with names like
input name="subnet"
input name="cidr"
input name="mask"
This is how the form collection will appear when the form gets posted. Unfortunately this will not bind to your Company model.
Your fields will need to look like this instead
input name="Company.pa_ipv4s[0].subnet"
input name="Company.pa_ipv4s[0].cidr"
input name="Company.pa_ipv4s[0].mask"
input name="Company.pa_ipv4s[1].subnet"
input name="Company.pa_ipv4s[1].cidr"
input name="Company.pa_ipv4s[1].mask"
There are multiple ways to "fix" this, and each has its own caveats.
One approach is to setup "Editor" views (typically in ~/Views/Shared/EditorTemplates/ClassName.cshtml), and then use #Html.EditorFor(x => x.SomeEnumerable). This will not work well in a scenario in which you need to be able to delete arbitrary items from the middle of a collection; although you can still handle those cases by means of an extra property like ItemIsDeleted that you set (e.g. via javascript).
Setting up a complete example here would be lengthy, but you can also reference this tutorial: http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/
As a start, you would create a simple template like
~/Views/Share/EditorTemplates/Contact.cshtml:
#model yournamespace.Contact
<div>
#Html.LabelFor(c => c.Name)
#Html.TextBoxFor(c => c.Name)
#Html.ValidationMessageFor(c => c.Name)
</div>
<div>
#Html.LabelFor(c => c.Email)
#Html.TextBoxFor(c => c.Email)
#Html.ValidationMessageFor(c => c.Email)
</div>
... other simple non-enumerable properties of `Contact` ...
#Html.EditorFor(c => c.pa_ipv4s) #* uses ~/Views/Shared/EditorTemplates/pa_ipv4s.cshtml *#
In your view to edit/create a Company, you would invoke this as
#Html.EditorFor(company => company.Contacts)
(Just like the EditorTemplate for Company invokes the EditorFor pa_ipv4s.)
When you use EditorFor in this way, MVC will handle the indexing automatically for you. (How you handle adding a new contact/IPv4/etc. here is a little more advanced, but this should get you started.)
MVCContrib also has some helper methods you can use for this, but it's not particularly simple from what I recall, and may tie you down to a particular MVC version.

Adding a save button to the index page

I have written an ASP.NET application that users access to check fields off. Instead of the user having to go into the edit page and hitting save, I want them to be able to just check it off on the index page and it either saves automatically or they can click the save button on the index page. I have made the fields EditorFor instead of Display for, and added the save button to the page. However, I am not sure how to implement the code to save in the controller.
Here is the code I have been trying out on my viewcontroller, but it says "does not contain a definition for save"
public virtual ActionResult Save(Doctor model)
{
Doctor.Save();
}
You are calling Save() on class Doctor which means there must be a static method in Doctor class. If it is not static but it does existing in the Doctor class then call the save method by model.Save().
If you are using EF then make sure inside the Save() method you're attaching the updated values on model object to respective EF entity or adding the object to the context in case new item is being created.
View
#using (Html.BeginForm("Save", "Doctor", FormMethod.Post))
{
<p>
#Html.LabelFor(model => model.Foo):
#Html.EditorFor(model => model.Foo)
#Html.ValidationMessageFor(model => model.Foo)
</p>
<p>
#Html.LabelFor(model => model.barImage)
<input type="file" name="Image" />
</p>
<p>
<input type="submit" value="Save" />
</p>
}
Controller
[HttpPost]
public ActionResult Create(Doctor doc)
{
your_dbcontext db = new your_dbcontext();
db.Add<Doctor>(doc);
db.SaveChanges();
return RedirectToAction("Index");
}

How can I pass a value from my page to the controller?

I'm using MVC with Razor and C#. I would like to update an element... a counter with ajax. Here is my code:
#model Domain.CounterObject
#using (Ajax.BeginForm("Count", "CounterObject", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "my-control" }))
{
<div id="my-control" class="bid-object">
<div>
<span class="title">#Html.Encode(Model.Title)</span>
</div>
<div>
<span class="display">#Html.Encode(Model.GetFinalDate())</span>
</div>
<div>
<span class="display">#Html.Encode(Model.GetValue())</span>
</div>
<div>
<input type="submit" value="Count" />
</div>
</div>
}
In my controller I have this code:
[HttpPost]
public PartialViewResult Count(CounterObject counter)
{
// Special work here
return PartialView(counter);
}
The problem is that my CounterObject counter I receive in my Count method is always null. How can I pass a value from my page to the controller?
I receive in my Count method is always null
First of all you are not submitting anything from the form then how does the binding happens?
If the user is not allowed to edit the values but still you want to submit them through the form then you have to use hidden fields along with them.
For ex.
<div>
<span class="title">#Html.Encode(Model.Title)</span>
#Html.HiddenFor(m => m.Title)
</div>
Note that the hidden fields should have the same names as the properties to make the binding happen successfully.
It is better to have properties in the Model that store the GetFinalDate() and GetValue() results so you can easily bind the things like in Title.
You'll have to define a input field with a name and id that the ModelBinder can then Bind to your CounterObject.
You could use #Html.EditorForModel once and then inspect the generated Html to see what kind of name/id pairs it is generating. With those you can go on and handcraft your Html if you wanted to.
use
<span class="title">#Html.Encode(Model.Title)</span>
<div class="editor-field">#Html.EditorFor(Model => Model.Title)<div>
//For other fields
In this way you can bind to your object.

mvc httppost href parameters

I'm currently working in ASP.NET MVC 4 with EF 4.0.
I have an unordered list with listitems. Each listitem contains a name and address and is clickable. Now I want to make it so that, when I click the listitem, I go to a new View. This view is called UitgebreidPersoonScherm and is in thesame controller RelatieZoekenController.
Here's the code I currently have:
Controller:
[HttpPost]
public ActionResult UitgebreidPersoonScherm(int psnID)
{
ViewBag.Message = "UitgebreidPersoonScherm";
return View("UitgebreidPersoonScherm");
}
View:
#model MobileApp.Models.ZoekModel
#{
ViewBag.Title = " Resultaten";
}
#using (Html.BeginForm("UitgebreidPersoonScherm", "RelatieZoeken", FormMethod.Post, new { id = "resultForm" }))
{ <ul data-role="listview" data-filter="true" data-inset="true" data-theme="g">
#foreach (var adres in Model.AdresList)
{
<li>
<a href='#Html.Action("UitgebreidPersoonScherm", "RelatieZoeken")'><b>#adres.Naam </b>
<br />#adres.Adres
</a></li>
}
</ul>
}
Now I wouldn't have a clue on how this is possible. I tried to make it with an actionlink, but it wouldn't show my data. If I remove the httppost I can get it to work, but without parameters. Currently it also doesn't give any parameters.
If you need any extra information, just ask.
Thanks.
but since you simply return the link, I advise you to substitute it somehow that way:
<a href='#Url.Action("UitgebreidPersoonScherm", "RelatieZoeken", new { psnID = adres.Id })'>

Categories

Resources