Suppose I have a simple model:
public class studentNames
{
string name{get; set;}
}
Now, if I scaffold it in view by create mode, only one model would be created. I want to create multiple objects in a single view.
Something like:
<form action="someAction">
Name of student1: <student1 name input box>
Name of student2: <student2 name input box>
<save button>
</form>
When this button would be clicked, a List would be returned in the controller, where I would be able to save them in database.
How can I achieve this?
Thanks in advance.
You could start by reading the convention that the model binder expects for binding to lists. And then name your input fields appropriately:
#using (Html.BeginForm("SomeAction", "SomeController"))
{
#for (var i = 0; i < 5; i++)
{
<div>
Name of student: #Html.TextBox("name[" + i + "]", null)
</div>
}
<button type="submit">Save</button>
}
and then your POST controller action could take a collection of students:
[HttpPost]
public ActionResult SomeAction(IList<StudentNames> students)
{
...
}
If you want to be able to dynamically add and remove items in this collection inside the view I would recommend you reading the Editing a variable length list article from Steven Sanderson where he illustrates a nice technique that would allow you to build such interface.
Related
I have a view, which simply does a foreach loop on a IEnumerable passed in the viewmodel, I have a way for people to select these entities on the list (apply a class to them to highlight), and this currently works for some clientside printing through jquery. Is there a way I can get these entities (staff) which have the highlight class and push them back as a model to the controller?
I have tried to use html.hiddenfor and just putting all the staff in there and making a form, with asp-action of my function on the controller and just a submit button, this did not work
the controller contains
public IActionResult StaffSelectionAction(StaffIndexModel model)
{
//things to do to process the selected staff
foreach (Staff staff in model.staff){
//Do stuff
}
return RedirectToAction("Index");
}
the view contains
<form asp-action="StaffSelectionAction">
#Html.HiddenFor(b => b.staff)
<input type="submit" value="Process Staff" class="btn btn-default" asp-action="StaffSelectionAction"/>
</form>
model contains
public IEnumerable<Staff> staff { get; set; }
Edit: spelling mistake in code
There are a few ways to handle this.
One way is to create an helper class, extending the Staff model and adding a 'selectable' attribute for it. Something like:
public class SelectableStaff : Staff
{
public bool Selected {get; set;}
}
Then in your view:
#Html.CheckBoxFor(m => m.Selected)
Using model binding, binding back to the controller with type SelectableStaff should then give you the selected values where you can do something like:
foreach (SelectableStaff staff in model.staff.Where(x => x.Selected)){
//Do stuff
}
You can get it back to Staff easily enough using linq and contains. Alternatively, you can also use #Html.Checkbox("myfriendlyname"), then include a FormCollection in the controller and pull the variable out of it. Personally, I think the model binding is less error prone.
I have main view and main model.
Inside this view i have such lines
foreach (var loadTask in Model.LoadTasks)
{
Html.RenderPartial("TripUpdateTask", new TripUpdateTaskModel { Task = loadTask });
}
So in main model i have the
public List<OrderTaskRecord> LoadTasks { get; set; }
Submodel is:
public class TripUpdateTaskModel
{
public OrderTaskRecord Task { get; set; }
}
I played and played but still unable to save the data. Here is current and simple look.
<tr>
<td>Actual Time:</td>
<td>#Html.TextBoxFor(m => m.Task.Task.ActualTime)</td>
</tr>
In raw html these time controls have same name and same id. So i dont know what need to do to save that.
I mean the data entered on main view back to controller fine, but not from partial view
I use Html.BeginForm and fieldset in main view like this:
#using (Html.BeginForm("TripUpdate", "SupplierBookingUpdate", FormMethod.Post, new { id = "SupplierBookingUpdateSave" }))
{
<fieldset>
.. table
</fieldset>
}
Rather than trying to name each text box individually, I would recommend to bind your collection of OrderTaskRecord. That way you do not need to worry about a number of text boxes and their names.
There's a good introduction from Scott Hanselman on the subject.
You can also try another example here: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/
If you want to pass a custom name to the input being generated use this. It passes the html attributes to the TextBoxFor method:
#Html.TextBoxFor(m => m.Task.Task.ActualTime, new { Name = "yourName" )
Of course, you can create counters, etc in here to keep them unique.
You can extract them later in your Controller by getting the Form data:
Request.Form["yourName"];
I've got a view that needs some checkboxes describing days of the week. I want to return back to the controller which boxes are selected. I found some help from various Google searches, etc, and here's what I have.
Section 1:
In the Controller:
vm.AllDays = Enum.GetValues(typeof(DayOfWeek)).Cast<DayOfWeek>().ToList();
In the View:
#foreach (var day in Model.AllDays) {
<input type="checkbox" name="days" value="#day"/> <label>#day</label><br />
}
And then in my post handler:
[HttpPost]
public ActionResult _AddEdit(SubscriptionDetailsModel vm, IEnumerable<string> days) {
//etc, etc, etc
}
This works, I get the selected days coming in on the days parameter. However, I got curious and changed the 'name' attribute on the checkboxes to the field in my model that I ultimately want these values to go to. In summary, my model for the view contains an object that has a List in it. That List is the collection I would like the selected values to end up in. But here's the relevant code.
Section 2
Model snippets:
public class SubscriptionDetailsModel {
public CronTabModel CrontabModel { get; set; }
//...
}
public class CronTabModel {
public List<DayOfWeek> On { get; set; }
}
Controller:
[HttpPost]
public ActionResult _AddEdit(SubscriptionDetailsModel vm) {
//etc, etc, etc
}
And, of course, view:
#foreach (var day in Model.AllDays) {
<input type="checkbox" name="On" value="#day"/> <label>#day</label><br />
}
Edit: The reason I was seeing confusing results is due to a typo elsewhere in my View.
Technically, the code in Section 1 is usable for my situation, I can do some string parsing, etc. Is it possible to make the Checkbox group populate from one collection (Model.AllDays) and return in a second collection (Model.CronTabModel.On)?
Model binding to a list is a bit awkward, but possible. MVC has an issue with gaps in indices, they did build in a helper to fix it. The hidden field lets MVC know about the gaps so it can bind effectively.
#for (var index =; index < Model.AllDays.Count(); index++) {
#Html.Hidden("AllDays.Index", index)
#Html.CheckBoxFor(m => Model.AllDays[Index], new { Value= Model.AllDays[index] }
<label>#Model.AllDays[Index]</label><br />
}
That should let you bind to a list of checkboxes that post their values back and are bound to a property called AllDays on your model.
If you want to change the name, you will need to change the name on your Model that you pass out. Doing it this way allows MVC to add the indexers onto the name, so you end up with
AllDays[0] = "Sunday"
AllDays[1] = "Monday"
Etc etc.
Some more reading about array binding http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
Every example that I can find of an MVC4 app has the edit working on one row of data at a time. It displays all the rows of data with each row having an edit which takes you to another page and allows you to edit that one row.
What I would like to do is display all the data elements in rows and instead of having the user have to click EDIT on each row, all the rows' data points would already be in text boxes which the user can directly update. And there is just one SAVE on the page that would just save all the updates/edits at once.
How can I setup my MVC app to support that?
You can use an EditorTemplates for this. The below example shows the normal form posting example. You can ajaxify it if you need by using the serialize method and sending form values.
Assuming You need to Edit the List of Student Names for a course. So Let's create some viewmodels for that
public class Course
{
public int ID { set;get;}
public string CourseName { set;get;}
public List<Student> Students { set;get;}
public Course()
{
Students=new List<Student>();
}
}
public class Student
{
public int ID { set;get;}
public string FirstName { set;get;}
}
Now in your GET action method, you create an object of our view model, initialize the Students collection and send it to our strongly typed view.
public ActionResult StudentList()
{
Course courseVM=new Course();
courseVM.CourseName="Some course from your DB here";
//Hard coded for demo. You may replace this with DB data.
courseVM.Students.Add(new Student { ID=1, FirstName="Jon" });
courseVM.Students.Add(new Student { ID=2, FirstName="Scott" });
return View(courseVM);
}
Now Create a folder called EditorTemplates under Views/YourControllerName. Then create a new view under that called Student.cshtml with below content
#model Student
#{
Layout = null;
}
<tr>
<td>
#Html.HiddenFor(x => x.ID)
#Html.TextBoxFor(x => x.FirstName ) </td>
</tr>
Now in our main view (StudentList.cshtml), Use EditorTemplate HTML helper method to bring this view.
#model Course
<h2>#Model.CourseName</h2>
#using(Html.BeginForm())
{
<table>
#Html.EditorFor(x=>x.Students)
</table>
<input type="submit" id="btnSave" />
}
This will bring all the UI with each of your student name in a text box contained in a table row. Now when the form is posted, MVC model binding will have all text box value in the Students property of our viewmodel.
[HttpPost]
public ActionResult StudentList(Course model)
{
//check for model.Students collection for each student name.
//Save and redirect. (PRG pattern)
}
Ajaxified solution
If you want to Ajaxify this, you can listen for the submit button click, get the form and serialize it and send to the same post action method. Instead of redirecting after saving, you can return some JSON which indicates the status of the operation.
$(function(){
$("#btnSave").click(function(e){
e.preventDefault(); //prevent default form submit behaviour
$.post("#Url.Action("StudentList",YourcontrollerName")",
$(this).closest("form").serialize(),function(response){
//do something with the response from the action method
});
});
});
You just need to specify the right model, list of example, and send the ajax with have information on each row (element of the array), read it on the server side and update each element accordingly. For this goal you use Post request. Just pass the list of elements as a parameters into the controller and pass it using the ajax.
For example you controller could be defined as:
public ActionResult Update(List<MyEntity> list)
{
...
}
public class MyEntity
{
public string Name {get; set;}
public int Count {get; set;}
}
and JavaScript could be as:
var myList = new Array();
// fill the list up or do something with it.
$.ajax(
{
url: "/Update/",
type: "POST",
data: {list: myList}
}
);
And of course your "Save" button has click event handler that will call that functionality with the ajax call.
For your convenience you can consider using KnockoutJS or other MVVM frameworks to bind the data with the DOM on the client side.
So I am new to ASP.NET MVC and I would like to create a view with a text box for each item in a collection. How do I do this, and how do I capture the information when it POSTs back? I have used forms and form elements to build static forms for a model, but never dynamically generated form elements based on a variable size collection.
I want to do something like this in mvc 3:
#foreach (Guest guest in Model.Guests)
{
<div>
First Name:<br />
#Html.TextBoxFor(???) #* I can't do x => x.FirstName here because
the model is of custom type Invite, and the
lambda wants to expose properties for that
type, and not the Guest in the foreach loop. *#
</div>
}
How do I do a text box for each guest? And how do I capture them in the action method that it posts back to?
Thanks for any help.
Definitely a job for an editor template. So in your view you put this single line:
#Html.EditorFor(x => x.Guests)
and inside the corresponding editor template (~/Views/Shared/EditorTemplates/Guest.cshtml)
#model AppName.Models.Guest
<div>
First Name:<br />
#Html.TextBoxFor(x => x.FirstName)
</div>
And that's about all.
Now the following actions will work out of the box:
public ActionResult Index(int id)
{
SomeViewModel model = ...
return View(model);
}
[HttpPost]
public ActionResult Index(SomeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// TODO: do something with the model your got from the view
return RedirectToAction("Success");
}
Note that the name of the editor template is important. If the property in your view model is:
public IEnumerable<Guest> Guests { get; set; }
the editor template should be called Guest.cshtml. It will automatically be invoked for each element of the Guests collection and it will take care of properly generating ids and names of your inputs so that when you POST back everything works automatically.
Conclusion: everytime you write a loop (for or foreach) inside an ASP.NET MVC view you should know that you are doing it wrong and that there is a better way.
You can do this:
#for (int i = 0; i < Model.Guests.Count; i++) {
#Html.TextBoxFor(m => m.Guests.ToList()[i].FirstName)
}
There are more examples and details on this post by Haacked.
UPDATE: The controller post action should look like this:
[HttpPost]
public ActionResult Index(Room room)
{
return View();
}
In this example I'm considering that you have a Room class like this:
public class Room
{
public List<Guest> Guests { get; set; }
}
That's all, on the post action, you should have the Guests list correctly populated.