I'm new to ASP.Net MVC and have a question regarding a master detail input form.
My database has a Child Table with foreign key relationships to the Physician, Immunization and Parent Table. I've used Linq to SQL to create my model.
I've created the controller and view for Child. The user will come to the form and submit everything all at once - a Child, their Physician info, one or many Parents and one or many Vaccinations.
I'm not sure how to approach this. Do I need a controller for Vaccinations, Parents etc?
My pre MVC app simply grabbed everything from the web form and populated all the
I typically have one controller that supports several views (add, edit, delete, etc.). I read from my database into a model that has fields for each piece of data that you want in the view. You then pass the model to the view so it can render it.
After the form is submitted, you'll get a model back from it as a parameter to the controller. You then update the database as needed.
Here's some code. I didn't try compiling it so your mileage may vary.
public class ParentModel
{
// Parent fields
public string FirstName { get; set; }
public string LastName { get; set; }
IList<ChildModel> Children { get; set; }
}
public class ChildModel
{
// Child fields
public int Age { get; set; }
}
public ActionResult MyAction()
{
// Grab a model with the children property filled out
ParentModel myModel = GetFromDatabase();
return View("MyView", myModel);
}
The view (abbreviated):
<%# Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<ParentModel>" %>
.
.
.
<% using (Html.BeginForm("MyAction", "MyController", FormMethod.Post)) %>
<% {%>
<%= Html.ValidationSummary(true) %>
<table>
<tr valign="top">
<td>
<%:Html.LabelFor(a => a.FirstName)%>:
</td>
<td>
<%:Html.EditorFor(a => a.FirstName)%>
<%:Html.ValidationMessageFor(a => a.FirstName)%>
</td>
</tr>
<tr valign="top">
<td>
<%:Html.LabelFor(a => a.LastName)%>:
</td>
<td>
<%:Html.EditorFor(a => a.LastName)%>
<%:Html.ValidationMessageFor(a => a.LastName)%>
</td>
</tr>
</table>
.
.
.
<%} %>
You only need the master controllers. The trick for editing list of thinks (the child objects) is explained in this haacked post
Basically you need to follow this conventions and MVC will fill an array of child object in the post method:
<% for (int i = 0; i < 3; i++) { %>
<%: Html.TextBoxFor(m => m[i].Title) %>
<%: Html.TextBoxFor(m => m[i].Author) %>
<%: Html.TextBoxFor(m => m[i].DatePublished) %>
<% } %>
Related
I am trying to put a checkboxlist onto a simple form in asp.NET MVC 2. This is the code for it:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm("HandSurvey", "Resources", FormMethod.Post, new { runat="server" }))
{ %>
<asp:CheckBoxList id="chkListChemical" runat="server">
<asp:ListItem>Fiberglass & resins</asp:ListItem>
<asp:ListItem>Heavy duty oil paints & stains</asp:ListItem>
<asp:ListItem>Mechanics - tools, grease/oil</asp:ListItem>
<asp:ListItem>Metalworking fluids</asp:ListItem>
<asp:ListItem>Paint & Stains in use</asp:ListItem>
<asp:ListItem>Exposure to solvents</asp:ListItem>
<asp:ListItem>Difficult soils</asp:ListItem>
<asp:ListItem>Hydrocarbons</asp:ListItem>
</asp:CheckBoxList>
<% }
%>
</asp:Content>
When I hit this page it gives this error:
Control 'ctl00_MainContent_chkListChemical_0' of type 'CheckBox' must be placed inside a form tag with runat=server.
I thought I was specifying the runat attribute correctly. Or is there something else that I am missing here? If I don't use the helper class and just use a regular form tag, it works.
In ASP.NET MVC you should avoid using server controls. Basically everything that has the runat="server" should not be used (except the content placeholder in WebForms view engine). In ASP.NET MVC you design view models:
public class MyViewModel
{
[DisplayName("Fiberglass & resins")]
public bool Item1 { get; set; }
[DisplayName("Heavy duty oil paints & stains")]
public bool Item2 { get; set; }
...
}
then you have controller actions that manipulate the view model:
// Action that renders the view
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
// Handles the form submission
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// TODO: Process the results
return View(model);
}
and finally you have a strongly typed view:
<% using (Html.BeginForm("HandSurvey", "Resources")) { %>
<div>
<%= Html.CheckBoxFor(x => x.Item1) %>
<%= Html.LabelFor(x => x.Item1) %>
</div>
<div>
<%= Html.CheckBoxFor(x => x.Item2) %>
<%= Html.LabelFor(x => x.Item2) %>
</div>
...
<p><input type="submit" value="OK" /></p>
<% } %>
UPDATE:
As requested in the comments section in order to have those checkboxes dynamically generated from a database it is a simple matter of adapting our view model:
public class ItemViewModel
{
public int Id { get; set; }
public string Text { get; set; }
public bool IsChecked { get; set; }
}
and now we will have our controller action to return a list of this view model:
public ActionResult Index()
{
// TODO: obviously those will come from a database
var model = new[]
{
new ItemViewModel { Id = 1, Text = "Fiberglass & resins" },
new ItemViewModel { Id = 2, Text = "Heavy duty oil paints & stains" },
};
return View(model);
}
and the view will now simply become:
<% using (Html.BeginForm("HandSurvey", "Resources")) { %>
<%= Html.EditorForModel() %>
<p><input type="submit" value="OK" /></p>
<% } %>
and the last part would be to define an editor template for our view model (~/Views/Shared/EditorTemplates/ItemViewModel.ascx):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.ItemViewModel>"
%>
<div>
<%= Html.HiddenFor(x => x.Id) %>
<%= Html.CheckBoxFor(x => x.IsChecked) %>
<%= Html.DisplayFor(x => x.Text) %>
</div>
This is related to ASP.Net MVC 2
I have a model (MoviesForAll) bound to my view and this model has a collection of class ICollection. I want my user to buy single ticket at a time by clicking submit button 'Buy this ticket' so I have placed a button besides each row representing the ticket details. This lead to following sequence
<%#Page Title="title" Language="C#" MasterPageFile="~/Views/Shared/MyMaster.Master"
Inherits="System.Web.Mvc.ViewPage<OnlineBooking.Movies.MoviesForAll>">
<Table>
<% for(i=0; i<Model.Tickets.count; i++)
{ %>
<tr>
<% using (Html.BeginForm(myaction(), FormMethod.Post, new {id="myform"}))
{ %>
<td>
<%= Model.tickets[i].ticketID %>
<%= Html.HiddenFor(m=>m.tickets[i].ticketID) %>
</td>
<td>
<%= Model.tickets[i].seatNo %>
<%= Html.HiddenFor(m=>m.tickets[i].seatNo) %>
</td>
...
...
<td>
<input type="submit" value="buy this ticket" runat="server">
</td>
<% } %>
</tr>
<% } %>
</table>
This creates a form for each row of tickets having single submit button in that form.
The problem is, when I submit first row (having index 0) by clicking the button, it gets submitted properly and I can see the values in controller method. But no other row gets through to controller even if I have used hidden fields to bind it.
Am I missing anything here specific to index or something?
Thanks in advance..
I would suggest having one form for all the rows, then on each row use the button element instead of an input as follows:
<button type="submit" value="<%= Model.tickets[i].ticketID %>" name="buyticket">Buy this ticket</button>
You should have a parameter on your controller action called buyticket and that should have the ticket id of the button which was clicked
How about the following:
<table>
<% for(i = 0; i < Model.Tickets.Count; i++) { %>
<tr>
<% using (Html.BeginForm("myaction", FormMethod.Post, new { id = "myform" })) { %>
<td>
<%= Model.tickets[i].ticketID %>
</td>
<td>
<%= Model.tickets[i].seatNo %>
</td>
...
...
<td>
<%= Html.Hidden("TicketId", Model.tickets[i].ticketID) %>
<%= Html.Hidden("SeatNumber", Model.tickets[i].seatNo) %>
<input type="submit" value="buy this ticket" />
</td>
<% } %>
</tr>
<% } %>
</table>
and then:
public class TicketToPurchaseViewModel
{
public int TicketId { get; set; }
public int SeatNumber { get; set; }
}
and the action:
[HttpPost]
public ActionResult myaction(TicketToPurchaseViewModel ticket)
{
...
}
Remark: notice that I have removed the runat="server" attribute from the submit button as well because this is something that you definitely don't want to see in an ASP.NET MVC application.
Getting data from view to create controller in asp.net MVC
I know this is very simple but I am just learning ASP.net MVC.
I have a Create controller and a create view (used the generator)
I can hard code data into the controller and that does get saved but I want to know how to get the data the user put on the form back into the controller.
My controller is like this.
public ActionResult Create(Seller newSeller)
{
if (ModelState.IsValid)
{
try
{
newSeller.SellerID = 34324442;
newSeller.State = "NA";
newSeller.UserType = "Seller";
newSeller.FirstName = "sdfasd";
newSeller.LastName = "dasdfadsf";
newSeller.Phone = "33333";
newSeller.Email = "dfasdfasdf";
// write to database
listingsDB.Sellers.AddObject(newSeller);
listingsDB.SaveChanges();
return RedirectToAction("Details", newSeller.SellerID);
}
catch(Exception ex)
{
}
}
return View(newSeller);
}
My view looks like this
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.SellerID) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.SellerID) %>
<%: Html.ValidationMessageFor(model => model.SellerID) %>
</div>
... Lots of propterties and then
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
I am using ASP.net MVC 2 if it matters.
You usually have two actions on the controller: one for rendering the form and one for processing the posted form values. Typically it looks like this:
public class SellerController: Controller
{
// used to render the form allowing to create a new seller
public ActionResult Create()
{
var seller = new Seller();
return View(seller);
}
// used to handle the submission of the form
// the seller object passed as argument will be
// automatically populated by the default model binder
// from the POSTed form request parameters
[HttpPost]
public ActionResult Create(Seller seller)
{
if (ModelState.IsValid)
{
listingsDB.Sellers.AddObject(seller);
listingsDB.SaveChanges();
return RedirectToAction("Details", new { id = seller.SellerID });
}
return View(seller);
}
}
then your view looks as you have shown, it contains a form and input fields allowing the user to fill each property of the model. When it submits the form, the second action will be invoked and the default model binder will automatically fill the action parameter with the values entered by the user in the form.
i have this problem :
when i try to post submit from a View to a httppost actionResult i get always a null value.
this is my code :
public class WhiteListViewModel
{
public string Badge { get; set; }
public IEnumerable<string> Selezioni { get; set; }
public IEnumerable<bool> Abilitazioni { get; set; }
}
public ActionResult WhiteList()
{
return View( "Whitelist", MasterPage, new WhitelistViewModel());
}
[HttpPost]
public ActionResult WhiteListp(IEnumerable<WhiteListViewModel> Whitelist )
{
bool[] abilitato = new bool[Whitelist.Single().Abilitazioni.Count()];
string[] selezione = new string[Whitelist.Single().Selezioni.Count()];
...
}
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/SiteR.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<_21112010.ViewModel.WhiteListViewModel>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
WhiteList
</asp:Content
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>WhiteList</h2>
<table style="width:100%;">
<thead>
</thead>
<tbody >
<%using ( Html.BeginForm( ) )
{%>
<% foreach ( var item in Model ){%>
<tr style="width:100%;">
<td >
<%: item.Badge%>
</td>
<%foreach ( var abit in item.Abilitazioni ){%>
<td >
<%: Html.CheckBoxFor(c=>abit/*, new { onchange = "this.form.submit();" } */ )%>
<%: Html.ValidationMessageFor(c => abit) %>
</td>
<% } %>
<%} %>
<td style=" width:1px;" >
<%: Html.HiddenFor(model=>item.Badge) %>
<% foreach (var sel in item.Selezioni) {%>
<%: Html.HiddenFor(c=>sel) %>
<%} %>
</td>
</tr> <%}%>
</tbody>
<tfoot>
</tfoot >
</table>
<input type="submit" value="Salva ed Esci" style = "background-color:Gray; color:#F6855E; font-weight:bold; border:1px solid black; height:20px;" />
<%:Html.ActionLink( "Aggiungi Badge", "AggiungiBadge")%>
<% } %>
</div>
</asp:Content>
where am I doing wrong?
The binding process will attempt to map the IEnumerable to the parameter Whitelist of the HttpPost action. However, I'm fairly sure that this is failing because the binding process has no information to tie the submitted fields to the expected parameter "Whitelist".
You have a few options:
Try using TryUpdateModel() in your action;
Creating a custom ModelBinder. This will allow you to interogate the submitted Model and build your IEnumerable prior to it being passed to the action parameter;
You could interogate the submitted fields using the FormCollection object from within the action. This is a little messy and not ideal;
Simplify your view.
Personally, I would look at the ModelBinder. If anything, this would give you a better insight into why the Model may not be binding to the action parameter.
I have a database with a one-to-many relationship that I'm having a difficult time modeling in ASP.NET MVC. For the sake of simplicity, let's say table A represents office buildings, table B represents employees and table C creates the one-to-many relation between employees and buildings to indicate which employees have access to a particular building.
Employee
EmployeeId - int
FirstName - string
LastName - string
Office
OfficeId - int
Location - string
EmployeeOffice
EmployeeId - int
OfficeId - int
When new employees come on board, I'd like to assign them to any office buildings they would be able to access. To do this, the UI calls for check boxes for each individual office building. Checking the boxes grants the user access to the related office building.
[ ] - Office 1
[ ] - Office 2
[ ] - Office 3
[ ] - Office 4
My concern is, offices should be dynamic. In other words, an office (or offices) can come or go at any time.
The model is actually more complicated than what I have depicted. As such, I have a CreateEmployeeViewModel, which contains properties (with annotations) as follows:
public class CreateEmployeeViewModel
{
public string FirstName
{
get;
set;
}
public string LastName
{
get;
set;
}
public IDictionary Offices
{
get;
private set;
}
public CreateEmployeeViewModel(IDictionary offices)
{
Offices = offices;
}
}
My view resembles the following
<div>
<%: Html.LabelFor(model => model.FirstName) %>
</div>
<div>
<%: Html.TextBoxFor(model => model.FirstName) %>
<%: Html.ValidationMessageFor(model => model.FirstName) %>
</div>
<div>
<%: Html.LabelFor(model => model.LastName) %>
</div>
<div>
<%: Html.TextBoxFor(model => model.LastName) %>
<%: Html.ValidationMessageFor(model => model.LastName) %>
</div>
<!-- This is really ugly, so I welcome any suggested updates -->
<% foreach (KeyValuePair<int, string> office in Model.Offices) { %>
<label for="Office<%: office.Key %>"><%: office.Value %></label>
<input id="Office<%: office.Key %>" type="checkbox" value="<%: office.Key %>" />
<% } %>
When I click the submit button for the form, I expect to get back the strongly typed view model, in addition to the check boxes so that I know which offices to assign users to. I created my action method like the following:
public ActionResult Create(CreateUserViewModel user, FormCollection collection)
The reason for the additional FormCollection object is I was hoping I could get form values in addition to the ones found on the view model (e.g., the check boxes). Unfortunately, however, the collection contains only information for the properties found in my view model.
What is the right way to handle forms with this design in ASP.NET MVC 2.0?
You need to add the "name" attribute to your checkbox input elements - otherwise they will not show up in the FormCollection.