how add a dropdownlist to my MVC3 application - c#

HELP:
i would like to add a dropdownlist to my MVC3 application using code first and c#.
i have 2 table Student and University, i need to put a dynamic list of university in a Create view of Student.
how and where should be add methode to my controller.
some one help me please
thanks

I'm guessing you are getting down votes because you could have just googled this and easily found the answer. Anyways, here's a link to get you started.
http://www.mikesdotnetting.com/Article/128/Get-The-Drop-On-ASP.NET-MVC-DropDownLists

The basic idea is you pass the drop down list as a property of the class that send to the view.
So something like this:
public Student
{
public List<University> Universities({//get list from database in getter
Then in the the view use something like
#Html.DropDownListFor(model => model.StudentsSchool, Model.Universities)

First create Entity class for your dropdown. It will return a list of value
public class KeyValueEntity
{
public string Description { get; set; }
public string Value { get; set; }
}
public class MyViewModel
{
public List<KeyValueEntity> Status { get; set; }
}
On your controller write the following code
[HttpGet]
public ActionResult Dropdown()
{
MyViewModel model = GetDefaultModel();
return View(model);
}
}
public MyViewModel GetDefaultModel()
{
var entity = new MyViewModel();
entity.Status = GetMyDropdownValues();
return entity;
}
private List<KeyValueEntity> GetMyDropdownValues()
{
return new List<KeyValueEntity>
{
new KeyValueEntity { Description = "Yes" , Value ="1" },
new KeyValueEntity { Description = "No" , Value ="0"}
};
}
Code for your cshtml page :
Now you need to bind your view with your model for this on top of your view you define your model class
#model MyViewModel
Following is the code for dropdown binding
#Html.LabelForModel("Status:")
#Html.DropDownListFor(m => m.Status, new SelectList(Model.Status, "Value", "Description"), "-- Please Select --")

Related

How to store multiple checkbox values in model and render them in view and controller in mvc4?

I am using ASP.NET MVC5 in my application.
I want to show languages known by an employee using check boxes in my view(check boxes with same name). For this how to write my model, pass them from the controller and display them in the view?
I have those vales stored in an Enum
public enum Language {
English=1,
Telugu=2,
Hindi=3,
Spanish=4
}
It is ok if I have to store them in a table in DB.
You can use the CheckBoxListFor helper:
#Html.CheckBoxListFor(model => model.SelectedOptions, Model.AllOptions)
And your model would look like this:
public class MyModel {
// This property contains the available options
public SelectList AllOptions { get; set; }
// This property contains the selected options
public IEnumerable<string> SelectedOptions { get; set; }
public MyModel() {
AllOptions = new SelectList(
new[] { "Option1", "Option2", "Option3" });
SelectedOptions = new[] { "Option1" };
}
}
In controller you just simply pass your model to the View:
[HttpGet]
[ActionName("Index")]
public ActionResult Index()
{
var model = new MyModel();
return View(model);
}
You can change the AllOptions and SelectedOptions properties as you want (just remove the code from the constructor of MyModel and place it in your controller class).
For more details check this out, there is a note about how to work with Enum: CheckBoxList for Enum types MVC Razor.

MVC - Populate Two Dropdowns From Database in Partial View with ViewModel

Here's the visual of what I'm trying to do.
So basically what happens here is that you choose a name from the select on the left and a team from the select on the right, then click Submit Assignment and it adds a record. (This information is for reference so you can understand the context. I don't need help with the database inserts or updates.)
This is going to be a PartialView with a ViewModel.
I need to know how to populate those two dropdowns with separate lists. I'm assuming those would be coming over in the ViewModel.
So in my main view, I have a call to the PartialView with RenderAction.
//The action //The controller
#{Html.RenderAction("TeamAssignment", "TeamAssignment");}
The controller that gets called
public class TeamAssignmentController : Controller
{
MyDatabaseEntities db = new MyDatabaseEntities();
[ChildActionOnly]
public ActionResult TeamAssignment()
{
//NEED A VIEW MODEL HERE TO PASS INTO THE PARTIALVIEW
return PartialView();
}
}
In the ViewModel I will need lists that populate the two drop downs.
The linq query on the left for Name would be this.
var nameList = (from p in db.Participant
where p.ParticipantType == "I"
select new {
p.ParticipantID,
p.IndividualName
}).ToList();
The linq query on the right for Team would be this.
var teamList = (from p in db.Participant
where p.ParticipantType == "T"
select new {
p.ParticipantID,
p.TeamName
}).ToList();
How can I pass that information into the PartialView and how do I populate the dropdowns with the ID for value and name for display text?
UPDATE
I belive this may be the ViewModel I need. Is this correct?
public class TeamAssignmentViewModel
{
//Need these ints for the updating and deleting
public int IndividualParticipantID { get; set; }
public int TeamParticipantID { get; set; }
public List<Participant> NameList { get; set; }
public List<Participant> TeamList { get; set; }
}
You need to create an instance of a viewmodel, populate it and pass it to your PartialView:
[ChildActionOnly]
public ActionResult TeamAssignment()
{
// Instantiate A VIEW MODEL HERE TO PASS INTO THE PARTIALVIEW
MyCustomModel model = new MyCustomModel();
model.nameList = (from p in db.Participant
where p.ParticipantType == "I"
select p).ToList();
model.teamList = (from p in db.Participant
where p.ParticipantType == "T"
select p).ToList();
return PartialView("TeamAssignment", model);
}
EDITED: removed use of dynamic class in linq statements
The markup for the Dropdowns might look something like:
#Html.DropDownListFor(model => model.IndividualParticipantID,
new SelectList(Model.NameList, "ParticipantID", "FirstName")
#Html.DropDownListFor(model => model.IndividualParticipantID,
new SelectList(Model.TeamList, "ParticipantID", "Team")
I'll start by admitting that I haven't read everything posted, but I can help with passing data to the PartialView to be used as a model.
In your View, you can build the partial like this:
#Html.Partial("_PartialViewName", currentItem,
new ViewDataDictionary {
{ "ExtraValue", Model.Count },
{ "SecondExtraValue", #ViewBag.ValueToPass });
Then in the PartialView, you can do this:
#model [Type of currentItem from above]
#{
// I'm using var here for shorthand, whereas I do strong typing and cast in my codebase.
var dataValue = ViewData["ExtraValue"];
var secondDataValue = ViewData["SecondExtraValue"];
}
Using this method you can pass in a model, as well as other values that may be needed for rendering.
Hope this helps. :)

How to send non model fields back to action form view

I have a view that has a model with a list of items I build as check box values. How can I post those values back to the action with the model? The problem is that there is not a concrete amount f check boxes, and they are sometimes unknown what the value will be. There could be 2 or there could be 15 depending on the user. but are built from the model's list values. Thanks in advance
You can use editor templates.
Assume, your view/page is to assign courses to students. So you will have a viewmodel like this
public class AssignCourseVM
{
public int StudentID { set;get;}
public string StudentName { set;get;}
public List<CourseRegistration> Courses { set;get;}
public AssignCourseVM()
{
Courses =new List<CourseRegistration>();
}
}
public class CourseRegistration
{
public int CourseID { set;get;}
public string CourseName { set;get;}
public bool IsRegistered { set;get;}
}
Now in your GET action, You will create an object of your viewmodel and send to the view
public ActionResult Registration()
{
var vm = new AssignCourseVM();
//Student Info is hard coded. You may get it from db
vm.StudentID = 1;
vm.StudentName = "Scott";
vm.Courses = GetCourseRegistations();
return View(vm);
}
public List<CourseRegistration> GetCourseRegistations()
{
var list = new List<CourseRegistration>();
//Hard coded for demo. You may load this list from DB
list.Add(new CourseRegistration { CourseID = 1, CourseName = "EN" });
list.Add(new CourseRegistration { CourseID = 2, CourseName = "GE" });
return list;
}
Now Let's create an Editor Template, Go to The View/YourControllerName and Create a Folder called EditorTemplates and Create a new View there with the same name as of the Property type (CourseRegistration.cshtml).
Now inside this new file, paste this content
#model ReplaceYourProjectNameSpaceHere.ViewModels.CourseRegistration
<div>
#Model.CourseName : #Html.CheckBoxFor(s=>s.IsRegistered)
#Html.HiddenFor(s => s.CourseID)
</div>
Now in our main view (Registration.cshtml) which is strongly typed to our AssignCourseVM class, we will use Html.EditorFor helper method.
#model ReplaceYourProjectNameSpaceHere.ViewModels.AssignCourseVM
<h2>Registration</h2>
#using(Html.BeginForm())
{
<h4>#Model.StudentName</h4>
#Html.EditorFor(s=>s.Courses)
#Html.HiddenFor(s=>s.StudentID)
<input type="submit" />
}
Now when user posts the form, You can inspect the posted viewmodel's course property to see which items are checked or not.
[HttpPost]
public ActionResult Registration(AssignCourseVM model)
{
//to do :save and redirect
return RedirectToAction("RegistrationSuccessfull");
}

Create (not read) field values into a new view in C# MVC

I've looked, tried several different solutions and haven't found anything that works (at least, not something with an example close enough to what I want for me to follow). I'm sure I'm missing something that would be a simple thing to a more experienced coder. Help?
I have a Model called Residents. It includes ResidentID, PFName, PLName. I have a controller for Residents. I have CRUD views for Residents. All working just fine.
I have a Model called Logs. It includes LogID, ResidentID, Comments. I have a controller for Logs. I have CRUD views for Logs. All working just fine.
I can display all the log entries for a Resident. Works fine. After a Log entry has been created, I can display the PFName using the method
#Html.DisplayFor(model => model.Resident.PFName)
Next, I want to Create a new log entry for a selected Resident.
That's where I'm having the problem. I would like the "Create" view (for the Log) to display the ResidentFName and ResidentLName of the selected resident, not the ResidentID.
A this point, from the Details view for a Resident, I have a CreateLog link.
#Html.ActionLink("New Log Entry", "../Log/Create", new { #ResidentID = Model.ResidentID})
This (likely not the best way) gives me a URL with the value of the selected ID
http://localhost:999/Log/Create?ResidentID=1
The value for the ResidentID is correct; it changes depending on which Resident is selected.
This value is correctly entered
#Html.TextBoxFor(model => model.ResidentID)
on the new CreateLog page using the Log Controller Create action.
public ActionResult Create(int ResidentID)
I plan to hide the ResidentID TextBox so the user doesn't see it. It seems I have to make it available in the form to be able create a new log entry.
The CreateLog form currently works as I have it now. I can create a log entry and verify that entry has been correctly recorded for the Resident.
But, I would like the form to display the PFName and PLName for the Resident so the user has visible feedback for which Resident was selected.
I believe that the related data (PFName and PLName) I want has to be passed to the CreateLog form .... somehow. I can't get it from the form.
Since there's only the unsaved entry for ResidentID, I can't use the value from the CreateLog form it to display related data. As mentioned, for the Lists, there is no such problem. It's only for CreateLog.
I've tried adding the data to the URL. Not working. I've tried setting the strings in the Controller (and the URL). Not working. I've looked at setting a cookie, but haven't ever done that so not sure what to set or where to put it or how to get the values from it. I've looked at setting a variable in the controller ... (have that working to display drop down lists, but a list to select from is not what I need -- I want the matching values from the related table).
Log.LogID(PK, Identity)
Log.ResidentID(FK)
Resident.PFName
Resident.PLName
I can directly create a view with these tables/fields in my SQLDB and update it.
Assuming a view model which looks something like this:
public class CreateLogViewModel
{
public int ResidentID { get; set; }
public string PFName { get; set; }
public string PLName { get; set; }
public string SomeLogCreationProperty { get; set; }
// other properties
}
Your controller could look something like this:
public ActionResult Create(int ResidentID)
{
var model = db.Residents.Where(r => r.ResidentID == ResidentID)
.Select(r => new CreateLogViewModel
{
ResidentID = r.ResidentID,
PFName = r.PFName,
PLName = r.PLName
// other properties
});
return View(model);
}
Then the view:
#model CreateLogViewModel
#using (Html.BeginForm())
{
#Html.HiddenFor(m => m.ResidentID)
#Html.HiddenFor(m => m.PFName)
#Html.HiddenFor(m => m.PLName)
#Html.EditorFor(m => m.SomeLogCreationProperty)
// other properties
<input type="submit" />
}
This would then POST back to:
[HttpPost]
public ActionResult Create(CreateLogViewModel model)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
// Redisplay the form with errors
return View(model);
}
Expanding on John H and StuartLC answers, you need to use ViewModels and the following workflow:
Database->(load)->Model->Controller->(convert)->ViewModel->View
and
View->ViewModel->Controller->(convert)->Model->(save)->Database
So lets says you have the following models:
namespace Models
{
public class Residents
{
public int ResidentID { get; set; }
public string PFName { get; set; }
public string PLName { get; set; }
//...
}
public class Logs
{
public int LogID { get; set; }
public int ResidentID { get; set; }
public string Comments { get; set; }
//...
}
}
You need a ViewModel that combines the data you need for display and input in your Log\CreateView:
namespace ViewModels
{
public class ResidentLog
{
public int ResidentID { get; set; }
public string PFName { get; set; }
public string PLName { get; set; }
public string Comments { get; set; }
//...
}
}
Then inside the controller:
public class LogController : Controller
{
[HttpGet]
public ActionResult Create(int ResidentID)
{
// Run in debug and make sure the residentID is the right one
// and the resident exists in the database
var resident = database.Residents.Find(residentID);
var model = new ViewModels.ResidentLog
{
ResidentID = resident.ResidentID,
PFName = resident.PFName,
PLName = resident.PLName,
Comments = string.Empty,
// ...
};
// Run in debug and make sure model is not null and of type ResidentLog
// and has the PFName and PLName
return View(model);
}
[HttpPost]
public ActionResult Create(ViewModels.ResidentLog model)
{
if (!ModelState.IsValid)
return View(model);
var log = new Models.Logs
{
// Assumes LogID gets assigned by database?
ResidentID = model.ResidentID,
Comments = model.Comments,
};
// Run in debug and make sure log has all required fields to save
database.Logs.Add(log);
database.SaveChanges();
return RedirectToAction("Index"); // Or anywhere you want to redirect
}
}
Then your Log\CreateView:
#model ViewModels.ResidentLog
<!-- Display the values needed -->
<div>#Model.ResidentID - #Model.PFName - #Model.PLName</div>
#using (var form = Html.BeginForm(...))
{
<!-- This saves the values for the post, but in fact only ResidentID is actually used in the controller -->
#Html.HiddenFor(m => m.ResidentID)
#Html.HiddenFor(m => m.PFName)
#Html.HiddenFor(m => m.PLName)
#Html.EditorFor(m => m.Comments)
<input type="submit" />
}
You need to provide the additional information to the view.
This can be done in at least 2 ways
Use the ViewBag dynamic as a quick and dirty cheap and cheerful container to pass everything the view needs from the controller.
(preferred) Use a custom ViewModel with a tailor made class which holds everything the view needs. This is generally preferred as it is statically typed.
(I'm assuming that resident is already persisted in the database by the time the Log controller is called - you might need to fetch it elsewhere)
So, in your log controller, here's an example of using ViewBag:
[HttpGet]
public ActionResult Create(int residentID)
{
ViewBag.Resident = Db.Residents.Find(residentId);
return View();
}
You can then show the resident properties on the view by utilizing the ViewBag.
Edit
Yes, by persisted I meant in the Db - apologies about using unclear jargon.
Here's another example of ViewBag approach (the idea is to create a new Comment for another object):
Doing this the cheap + cheesy ViewModel way - in the HTTPGet Controller Create method:
public ActionResult Create(string objectType, int objectId)
{
// This is equivalent to youn fetching your resident and storing in ViewBag
ViewModel.Object = FetchSomeObject(objectType, objectId);
return View();
}
And in the View I use this (The ViewBag is accessible to Controller and View):
<title>#string.Format("Add new Comment for {0} {1}", ViewBag.Object.ObjectType, ViewBag.Object.Name);</title>
As you say, you will also need to do add a hidden for the ResidentId in your create log form
As per #JohnH's answer (+1), the BETTER way to do this (than using the magic ViewBag dynamic) is to create a custom ViewModel specifically for this screen. The ViewModel can either be reused both ways (GET: Controller => View and POST : Browser => Controller, or you even have separate ViewModels for the Get and Post legs.
With much thanks to all, I have it working. The final piece was telling the controller to return the model (nl). Here's the full spec for what's working:
I have created a ViewModel that includes
public class NewLog
{
public int ResidentID { get; set; }
public string PFName { get; set; }
public string PLName { get; set; }
public string Comment { get; set; }
// other properties
}
In the LogController,
public ActionResult Create(int ResidentID)
{
var resident = db.Residents.Find(ResidentID);
var nl = new NewLog
{
ResidentID = ResidentID,
PFName = resident.PFName,
PLName = resident.PLName,
Comment = string.Empty,
};
return View(nl);
}
In the Create.cshtml page,
#model My.Models.NewLog
The required ResidentID to be recorded with the new Log Entry
#Html.TextBoxFor(model => model.ResidentID, new {#Type = "Hidden"})
And the related, user-friendly display boxes for the person's name
#Html.DisplayFor(model => model.PFName)
#Html.DisplayFor(model => model.PLName)
And in the URL which is used to access the create page,
#Html.ActionLink("New Log Entry", "../Log/Create", new { #ResidentID = item.ResidentID, item.PFName, item.PLName})

How to add values to dropdown in MVC3?

I want to add a dropdownlist in my form, with 2 values userid and username in my dropdownlist, and also I want to get the value selected by the user when I click the button. I'm new to MVC and so far, I have not worked on dropdownlist, tried few samples but nothing seems to be working the way I want.
I'll jump lots of MVC3 concepts. If you're really new to ASP.NET MVC, you should take a look at some tutorials.
This code should help you:
VIEW
#using (Html.BeginForm("ACTION NAME", "CONTROLLER NAME"))
{
<select name="select">
<option value="username" selected>User name</option>
<option value="userid">User id</option>
</select>
<input type="submit" />
}
ACTION
[HttpPost]
public ActionResult ACTIONNAME(string select)
{
//...
}
Please, note:
ACTION NAME and CONTROLLER NAME at the BeginForm helper. You will have to modify this at your code
The select name ("select") and the name of the argument at the action ("select"). This is not a coincidence, it's a convention. MVC uses the name attr to bind data
The selected attribute at the option will make it the default option
Regards
See one of the ways you can do it is send the list in a model property as the binding and for the value you can bind it to another property like :
public class YourModel
{
public List<UserList> OptionList { get; set; }
public String YourValue{get;set;}
}
public class UserList
{
public String UserName{get;set;}
public String UserId{get;set;}
}
#Html.DropDownListFor(model => model.YourValue, Model.OptionList, "")
In the helper there are overided options which are used to specify the value and text.
And Remember :
This is StackOverflow.
Even the Not working example which you have tried are important for the ones who try to help you since they are spending their precious bandwidths for u.
You don't need create a new model class for each view, just put this on controller:
ViewBag.FieldName = new SelectList(new List<SelectListItem>() {
new SelectListItem { Value = "userid", Text = "User ID" },
new SelectListItem { Value = "username", Text = "User name" }
});
And this on view:
#Html.DropDownList("FieldName")
You need to create a collection of SelectListItem like:
IEnumerable<SelectListItem> selectList =
from c in areaListResponse.Item
select new SelectListItem
{
Text = c.AreaName,
Value = c.Id.ToString()
};
Pass this selectList to your view:
return View(selectList);
In your cshtml:
#model IEnumerable<SelectListItem>
#Html.DropDownListFor(m => m.RequestAreaName, Model)
If you need complecated object, you may need a wrapper class like:
public class RaiseRequestModelWrapper
{
public IEnumerable<SelectListItem> GetModel { get; set; }
public RaiseRequestModel PostModel { get; set; }
}

Categories

Resources