Passing data from View to Controller in ASP.NET MVC - asp.net

I have a model class Person
public class Person
{
public string name { get; set; }
public string area { get; set; }
}
Now, in my Index view, I want to pass values from view to controller by taking value name property from user and area ="foo".I know how I can take values from user by like below
#using (Html.BeginForm())
{
#Html.Label("Name")
#Html.TextBoxFor(m=>m.name)
<input type="submit" value="Name" />
}
Now, I want area ="foo" in views.I tried to google the problem,I did not find the solution.
This is general problem.Do not answer like ,set value area="foo" in controller.
Please help me and don't downvote without commenting so that I can improve my question in future.
Thanks

Add a hidden field to your form with name "area" and set the value as whatever you want. When your form is posted, the hidden field value will be also posted to your action method.
#using (Html.BeginForm())
{
#Html.Label("Name")
#Html.TextBoxFor(m=>m.name)
<input type="hidden" name="area" value="foo" />
<input type="submit" value="Name" />
}
Now you can get this in your HttpPost action method
[HttpPost]
public ActionResult Create(Person model)
{
// check for model.name and model.area.
// TO DO : Save and redirect
}
You should remember that, people can always update the hidden field value in the browser using some tools like firebug or so. If it is a sensitive information (Price of an item in a shopping portal) , don't read like this from client. Read it from server.

Related

How to get the user entered data from view to controller and then insert into database, in MVC?

I am a beginner and currently started a small project for my study purpose. A mini DB search portal. I created front end View. It has one search box and a button. Now what I need is, I have to fetch the data from DB, related to the user entered search term on clicking on the button.
How to proceed to get the user entered data from view to controller and process it for further operations.
General code:
view:
#using(Html.BeginForm("Search","Test"))
{
<input type="text" name="txtName"/>
<input type="submit" value="Generate report" />
}
Controller
[HTTPPost]
public ActionResult Seacrh(FormCollection form) // "Search" is action name specified in view for controller "TestController"
{
string text = form["txtName"]; // txtName is name of input in view.
}
However to take full advantage to MVC have a look at Model Binding in MVC
I recommend reading this article, it has an example different ways of adding search.
You can update the Index method in your Controller and View as follows:
1)Add a form to the view that will post to the view itself
View
#using (Html.BeginForm()){
<p> Title: #Html.TextBox("SearchString") <br />
<input type="submit" value="Filter" /></p>
}
2)Add a parameter to the Index method to filter the content based on the parameter passed. public ActionResult Index(string searchString)
Controller
var movies = from m in db.Movies
select m;
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
return View(movies);

How to pass a list of object from view to controller in mvc3?

public class EmployeeViewModel
{
public Employee Employee { get; set; }
public IList<Address> Addresses { get; set; }
}
Controller :-
[HttpPost]
public ActionResult InsertAddress(EmployeeViewModel model)
{
//code for insert data into db
}
View :-
Here i want to call InsertAddress action by passing multiple address objects along with single employee object from view to controller .
Is it possible ?
You just need to use the correct naming conventions for the model binder to understand.
Property.Property
Or
Property[index].Property for Collections
If index isn't sequential 0 based you need to add a hidden field, Property.Index with the value of the index
Example:
<input name="Employee.Name" value="1234 5678"/>
<input name="Employee.Phone value="1234 5678"/>
<input name="Employee.Email" value="me#example.com"/>
<input name="Addresses.Index" value="0" type="hidden"/>
<input name="Addresses[0].Suburb" value="Melbourne"/>
<input name="Addresses[0].Postcode" value="3000"/>
<input name="Addresses.Index" value="1" type="hidden"/>
<input name="Addresses[1].Suburb" value="Sydney"/>
<input name="Addresses[1].Postcode" value="2000"/>
When your inserting a row, just use the naming convention, and don't forget to add the .Index field.
Most the default EditorFor will handle all of this for you transparently if you create a custom EditorTemplate for your Address class.
Yes it possible, but requires a little work on your part.
Rather than having a single view for the model (with some sort of loop for the addresses), you need to create an EditorTemplate for your Address class, and then in the main view use #Html.EditorFor(m => m.Addresses)
This setup will cause your EmployeeViewModel instance to be returned to your action containing the full list of Addresses (rather than it being empty).
I have mentioned some common issues while binding complex models, have a look here
http://jayakarant.blogspot.de/2014/05/handling-complex-view-models-in-razor.html

Asp.net mvc3 razor with multiple submit buttons

I'm using MVC3 Razor. I have 2 submit buttons setup on my view but the problem I'm having is that both submit buttons cause the validation of the model. I want to hook up individual submit buttons with specific input controls for validation.
I know this is a few months old but the solutions here seemed needlessly complex and there's no accepted answer yet. If you name your inputs the same but give them different values, you can get that value in your controller just by including a string with the name of the input as a variable. This is how I solved this problem:
View:
<input type="submit" id="EnterprisePush" name="btnSubmit" value="Push" />
<input type="submit" id="EnterprisePull" name="btnSubmit" value="Pull" />
Controller:
[HttpPost]
public ActionResult EnterpriseAdmin(int id, string btnSubmit, FormCollection collection)
{
switch (btnSubmit) {
case "Push":
/* Do Something here */
break;
case "Pull":
/* Do Something else here */
break;
}
The browser is always going to submit the entire form regardless of which submit button you press.
The best solution would be to have two submit buttons with the same value for the name attribute and different values for the value attributes.
When you submit the form, the value of the button will be submitted as well. In your action which handles that form submission, you check to see the value of the button and perform the correct validation based on that.
In your form you would have something like this:
<button type="submit" name="Command" value="command1">Do Command #1</button>
<button type="submit" name="Command" value="command2">Do Command #2</button>
Your Form Model would look like this:
public class MyFormModel() {
public string Command {get;set;}
public string SomeOtherVal {get;set;}
}
Your controller\action would look like this:
public ActionResult HandleFormSubmit(MyFormModel model) {
if (model.Command == "command1") {
// do something
} else if (model.Command == "command2") {
// do something else
}
}
Firstly, you can disable client validation on your cancel button simply by adding the CSS class 'cancel' to it. See: Disable client-side validation in MVC 3 "cancel" submit button
Secondly, as well testing the submit element's form name as described above, you can use a custom action selector. Here's mine, which I originally took from the blog post shown in the comment:
/// <summary>
/// Used to vary an action method based on which button in a form was pressed. This
/// is useful but is an anti-pattern because it couples the controller to names
/// used in the form elements.
/// </summary>
/// <remarks>
/// See the example at http://weblogs.asp.net/dfindley/archive/2009/05/31/asp-net-mvc-multiple-buttons-in-the-same-form.aspx
/// </remarks>
public class AcceptButtonAttribute : ActionMethodSelectorAttribute
{
public string ButtonName { get; set; }
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
var req = controllerContext.RequestContext.HttpContext.Request;
return !string.IsNullOrEmpty(req.Form[this.ButtonName]);
}
}
In your controller:
[HttpPost]
[ActionName("Edit")]
[AcceptButton(ButtonName = "Cancel")]
public ActionResult Edit_Cancel(MyModel model)
{
return RedirectToAction("Index");
}
[HttpPost]
[AcceptButton(ButtonName = "Save")]
public ActionResult Edit(MyModel model)
{
// do real work here
}
Note that you need the [ActionName("Edit")] attribute to tell MVC that although using a different method name, it is for the Edit action.
And in your View:
<input type="submit" name="Save" value="Save" />
<input type="submit" name="Cancel" value="Cancel" class="cancel" />
My solution was to do two things. Say we have a Save button and another Add Something button. When user clicks on Save we want client validation and server validation to be performed. For later button we don't want any validation to take place.
Temporarily disable client validation for second button (on click):
<input type="submit" name="submit-button" value="Save" />
<input type="submit" name="submit-button" value="Add Something" onclick="document.forms[0].noValidate = true; document.forms[0].submit();" />
Good thing about it is when JavaScript is disabled the client validation would never have taken place anyway.
Take care of server side
Similar to what Bryan is saying when you click any submit button within a form, the entire form and the clicked submit button value is posted. You can differentiate which button was clicked by the name posted. In example above when user clicks on Save button and we read Request.Form["submit-button"] in controller post action we get "Save". If user clicked on Add Something we would get "Add Something". This is the way HTML is supposed to work.
Now to get around having magic strings all over the place I usually have a public static class within the controller, like so:
public class HomeController
{
public static class Buttons
{
public const string Save = "Save";
public const string AddSomething = "Add something";
}
// Action methods
}
So you can use these for rendering form:
<input type="submit" name="submit-button" value="#HomeController.Buttons.Save" />
And you can easily read the button clicked in controller:
[HttpPost]
public ActionResult Index(Model viewModel)
{
var buttonClicked = Request.Form["submit-button"];
switch (buttonClicked) {
case HomeController.Buttons.Save:
return Save(viewModel);
case HomeController.Buttons.AddSomething:
return AddSOmething(viewModel);
}
return View();
}
In Save method you first ask if ModelState.IsValid and return view model if not but in AddSomething method we will clear any errors:
public ActionResult AddSomething(Model viewModel)
{
ModelState.Clear();
// your code to add something to model
return View(viewModel);
}
This was you keep everything clean, tidy and testable. And you can introduce a constant for submit-button html name attribute. It might be possible to do all the constants with T4MVC too. A similar solution applies to when you need a "auto postback" combo box, except you need a hidden field that is set via onchange event of the select element.
Hope this helps.
Just use this code as a template:
#{
var nextButtonVal = "Next >>";
var backButtonVal = "<< Back";
if (IsPost) {
if(Request["navigate"].Equals(backButtonVal)){Response.Redirect("~/pageFoo");}
if(Request["navigate"].Equals(nextButtonVal)){Response.Redirect("~/pagebar");}
}
}
<input type="submit" value="#backButtonVal" title="Back" name="navigate"/>
<input type="submit" value="#nextButtonVal" title="Next" name="navigate"/>
One final thing I would do is instead of using intelligent strings, use an enum to determine the value for each input tag. Using razor syntax:
#Enum.GetName(typeof(YourEnumType), yourEnum.WhateverValue)
then in your controller:
public ActionResult DoSomethingBasedOnEnumValue(string enumValue)
{
YourEnumType localVar = (YourEnumType)Enum.Parse(typeof(YourEnumType), enumValue);
switch(localVar)
{
case YourEnumType.Action1:
//do something
break;
case YourEnumType.Action2:
//do something else
break;
}
return View();
}
If you want to have separate action for delete, try this.
add a delete action in the controller and mark it as HttpDelete,
[HttpDelete]
public ActionResult Edit(int id, string foo) {
...
}
And in the view,
button name should be X-HTTP-Method-Override and value should be DELETE
<button name="X-HTTP-Method-Override" value="DELETE" formnovalidate="formnovalidate" class="cancel">Delete</button>
note: all most all the browsers don't allow for other HTTP methods, like HEAD, PUT, or DELETE. but by add a header to the HTTP request, X-HTTP-Method-Override, that is supposed to be interpreted by the service and acted upon regardless of the actual HTTP method used. So above code will add a header to the request like X-HTTP-Method-Override: DELETE. and .net framework will do the rest of the things and direct you to delete action.
Submit button name don't come to server side if in all from this situation you are will be use [Remote] attribute for validation model property.

How to retrieve form values from HTTPPOST, dictionary or?

I have an MVC controller that has this Action Method:
[HttpPost]
public ActionResult SubmitAction()
{
// Get Post Params Here
... return something ...
}
The form is a non-trivial form with a simple textbox.
Question
How I access the parameter values?
I am not posting from a View, the post is coming externally. I'm assuming there is a collection of key/value pairs I have access to.
I tried Request.Params.Get("simpleTextBox"); but it returns error "Sorry, an error occurred while processing your request.".
You could have your controller action take an object which would reflect the form input names and the default model binder will automatically create this object for you:
[HttpPost]
public ActionResult SubmitAction(SomeModel model)
{
var value1 = model.SimpleProp1;
var value2 = model.SimpleProp2;
var value3 = model.ComplexProp1.SimpleProp1;
...
... return something ...
}
Another (obviously uglier) way is:
[HttpPost]
public ActionResult SubmitAction()
{
var value1 = Request["SimpleProp1"];
var value2 = Request["SimpleProp2"];
var value3 = Request["ComplexProp1.SimpleProp1"];
...
... return something ...
}
Simply, you can use FormCollection like:
[HttpPost]
public ActionResult SubmitAction(FormCollection collection)
{
// Get Post Params Here
string var1 = collection["var1"];
}
You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:
//Defined in another file
class MyForm
{
public string var1 { get; set; }
}
[HttpPost]
public ActionResult SubmitAction(MyForm form)
{
string var1 = form1.Var1;
}
The answers are very good but there is another way in the latest release of MVC and .NET that I really like to use, instead of the "old school" FormCollection and Request keys.
Consider a HTML snippet contained within a form tag that either does an AJAX or FORM POST.
<input type="hidden" name="TrackingID"
<input type="text" name="FirstName" id="firstnametext" />
<input type="checkbox" name="IsLegal" value="Do you accept terms and conditions?" />
Your controller will actually parse the form data and try to deliver it to you as parameters of the defined type. I included checkbox because it is a tricky one. It returns text "on" if checked and null if not checked. The requirement though is that these defined variables MUST exists (unless nullable(remember though that string is nullable)) otherwise the AJAX or POST back will fail.
[HttpPost]
public ActionResult PostBack(int TrackingID, string FirstName, string IsLegal){
MyData.SaveRequest(TrackingID,FirstName, IsLegal == null ? false : true);
}
You can also post back a model without using any razor helpers. I have come across that this is needed some times.
public Class HomeModel
{
public int HouseNumber { get; set; }
public string StreetAddress { get; set; }
}
The HTML markup will simply be ...
<input type="text" name="variableName.HouseNumber" id="whateverid" >
and your controller(Razor Engine) will intercept the Form Variable "variableName" (name is as you like but keep it consistent) and try to build it up and cast it to MyModel.
[HttpPost]
public ActionResult PostBack(HomeModel variableName){
postBack.HouseNumber; //The value user entered
postBack.StreetAddress; //the default value of NULL.
}
When a controller is expecting a Model (in this case HomeModel) you do not have to define ALL the fields as the parser will just leave them at default, usually NULL. The nice thing is you can mix and match various models on the Mark-up and the post back parse will populate as much as possible. You do not need to define a model on the page or use any helpers.
TIP: The name of the parameter in the controller is the name defined
in the HTML mark-up "name=" not the name of the Model but the name of the expected variable in the !
Using List<> is bit more complex in its mark-up.
<input type="text" name="variableNameHere[0].HouseNumber" id="id" value="0">
<input type="text" name="variableNameHere[1].HouseNumber" id="whateverid-x" value="1">
<input type="text" name="variableNameHere[2].HouseNumber" value="2">
<input type="text" name="variableNameHere[3].HouseNumber" id="whateverid22" value="3">
Index on List<> MUST always be zero based and sequential. 0,1,2,3.
[HttpPost]
public ActionResult PostBack(List<HomeModel> variableNameHere){
int counter = MyHomes.Count()
foreach(var home in MyHomes)
{ ... }
}
Using IEnumerable<> for non zero based and non sequential indices post back. We need to add an extra hidden input to help the binder.
<input type="hidden" name="variableNameHere.Index" value="278">
<input type="text" name="variableNameHere[278].HouseNumber" id="id" value="3">
<input type="hidden" name="variableNameHere.Index" value="99976">
<input type="text" name="variableNameHere[99976].HouseNumber" id="id3" value="4">
<input type="hidden" name="variableNameHere.Index" value="777">
<input type="text" name="variableNameHere[777].HouseNumber" id="id23" value="5">
And the code just needs to use IEnumerable and call ToList()
[HttpPost]
public ActionResult PostBack(IEnumerable<MyModel> variableNameHere){
int counter = variableNameHere.ToList().Count()
foreach(var home in variableNameHere)
{ ... }
}
It is recommended to use a single Model or a ViewModel (Model contianing other models to create a complex 'View' Model) per page. Mixing and matching as proposed could be considered bad practice, but as long as it works and is readable its not BAD. It does however, demonstrate the power and flexiblity of the Razor engine.
So if you need to drop in something arbitrary or override another value from a Razor helper, or just do not feel like making your own helpers, for a single form that uses some unusual combination of data, you can quickly use these methods to accept extra data.
If you want to get the form data directly from Http request, without any model bindings or FormCollection you can use this:
[HttpPost]
public ActionResult SubmitAction() {
// This will return an string array of all keys in the form.
// NOTE: you specify the keys in form by the name attributes e.g:
// <input name="this is the key" value="some value" type="test" />
var keys = Request.Form.AllKeys;
// This will return the value for the keys.
var value1 = Request.Form.Get(keys[0]);
var value2 = Request.Form.Get(keys[1]);
}

Accessing models from view in MVC 2 Timesheet application?

I am trying to create a timesheet application in MVC 2, but I feel like I am still struggling to grasp the model/view relationships and all that.
The problem I have is, I want to let the user report a new time segment in a create view. But I want to have dropdownlists populated with Projects, Tasks, and Consultants from the model.
Basically the database structure looks like this:
(table) TimeSegments
TimeSegmentID
Hours
Date
ConsultantID (FK)
TaskID (FK)
ProjectID (FK)
(table) Projects
ProjectID
ProjectName
(table) Tasks
TaskID
TaskName
(table) Consultants
ConsultantID
ConsultantName
This design may be extended in future, right now I want to get basic functionality working before I complicate it further.
Now, I am passing the entire model to the create view (actually a viewmodel based on it, just to simplify some coding, but it might as well have been the entire model).
The problem is, normally when I have done similar things with a create view, I would have created a new object in the controller and passed that to the view. In this case it would have been the TimeSegment object, since it is a new time segment that should be created in the database. Then I could just submit it and update the database in the controller. However, if I only pass a new TimeSegment object to the view, I can't populate the dropdownlists with Projects, Tasks and Consultants.
And oppositely, if I only pass the entire model, how would I bind a textbox to a new TimeSegment to be updated in the database?
I feel like I need to send both a new TimeSegment object and the entire model to do this, but then I have no idea how I would access it (there's only that one "Model" to access from the view). Also, back in the controller after a submit, how would the controller know what to update?
I'm sure I'm just thoroughly confused still by the MVC way of thinking, but I would really appreciate it if someone could clarify this for me and tell me (as pedagogically as possible) what to do to solve this.
Okay, I will give it a shot.
MVC is not hard, but you do have to alter your way of thinking a bit. In MVC you have the Models (your data layer[s]), the Views and the Controllers.
Before we continue, I make the assumptions with my examples below that you are using LINQ to SQL for you data access layer (Model), and I have labeled it as dc.
The Controllers fetch and format the data out of the Models and hand it off to the Views to display. So lets start with your first view which would be the view to create a TimeSegment.
[HttpGet]
public ActionResult CreateTimeSegment() {
return View(new TimeSegmentView {
Consultants = dc.Consultants.ToList(),
Projects = dc.Projects.ToList(),
Tasks = dc.Tasks.ToList()
});
}
This action will create a TimeSegmentView object and pass that to the View as its Model. Keep in mind that this action is decorated with [HttpGet]. TimeSegmentView` is a container class for the objects you need to pass to the view to create your UI and it looks like this:
public class TimeSegmentView {
public IList<Consultant> Consultants { get; set; }
public IList<Project> Projects { get; set; }
public IList<Task> Tasks { get; set; }
public TimeSegment TimeSegment { get; set; }
}
NOTE: I'm not using the TimeSegment property yet, it's further down...
In the view make sure you have it inherit from TimeSegmentView. Assuming that you're following the default MVC project structure and with me taking the liberty to add a Views folder into the Models folder your full reference would look like this:
<%# Page Inherits="System.Web.Mvc.ViewPage<PROJECTNAME.Models.Views.TimeSegmentView>" %>
Now you've typed the view to that object and you can now interact with its properties. So, you can build a form such as:
<form action="/" method="post">
<p>
<label>Hours</label>
<input name="TimeSegment.Hours" />
</p>
<p>
<label>Date</label>
<input name="TimeSegment.Date" />
</p>
<p>
<label>Consultant</label>
<select name="TimeSegment.ConsultantID">
<% foreach (Consultant C in Model.Consultants) { %>
<option value="<%=C.ConsultantID%>"><%=C.ConsultantName%></option>
<% }; %>
</select>
</p>
<p>
<label>Project</label>
<select name="TimeSegment.ProjectID">
<% foreach (Project P in Model.Projects) { %>
<option value="<%=P.ProjectID%>"><%=P.ProjectName%></option>
<% }; %>
</select>
</p>
<p>
<label>Task</label>
<select name="TimeSegment.TaskID">
<% foreach (Task T in Model.Tasks) { %>
<option value="<%=T.TaskID%>"><%=T.TaskName%></option>
<% }; %>
</select>
</p>
</form>
As you can see it created 3 select fields and just performed loops in each of them to build up their values based off of the model.
Now, taking a submission of this form, we'll need to get the data and add it to our database with:
[HttpPost]
public RedirectToRouteResult CreateTimeSegment(
[Bind(Prefix = "TimeSegment", Include = "Hours,Date,ConsultantID,ProjectID,TaskID")] TimeSegment TimeSegment) {
dc.TimeSegments.InsertOnSubmit(TimeSegment);
dc.SubmitChanges();
return RedirectToAction("EditTimeSegment", new {
TimeSegmentID = TimeSegment.TimeSegmentID
});
}
Okay, first notice that I've named the action the same, but this one has an [HttpPost] decoration. I'm telling the action that I'm sending it a TimeSegment object and that I want it to bind the properties in the Include clause (this is mostly for security and validation). I then take the TimeSegment object I've passed in, add it to the data context, submit the changes and redirect. In this case I'm redirecting to another action to edit the object I just created passing in the new TimeSegmentID. You can redirect to what ever, this just felt appropriate to me...
[HttpGet]
public ActionResult EditTimeSegment(
int TimeSegmentID) {
return View(new TimeSegmentView {
Consultants = dc.Consultants.ToList(),
Projects = dc.Projects.ToList(),
Tasks = dc.Tasks.ToList(),
TimeSegment = dc.TimeSegments.Single(t => t.TimeSegmentID == TimeSegmentID)
});
}
In the edit action your doing the same thing as in the create action by building a new TimeSegmentView object and passing it to the view. The key difference here is that you're now populating the TimeSegment property. Your form would look something like this (shortened from above):
<form action="/<%=Model.TimeSegment.TimeSegmentID%>" method="post">
<p>
<label>Hours</label>
<input name="TimeSegment.Hours" value="<%=Model.TimeSegment.Hours%>" />
</p>
</form>
And your receiving action on the controller would look like this:
[HttpPost]
public RedirectToRouteResult EditTimeSegment(
int TimeSegmentID) {
TimeSegment TS = dc.TimeSegments.Single(t => t.TimeSegmentID == TimeSegmentID);
TryUpdateModel<TimeSegment>(TS, "TimeSegment", new string[5] {
"Hours", "Date", "ConsultantID", "ProjectID", "TaskID"
});
dc.SubmitChanges();
return RedirectToAction("EditTimeSegment", new {
TimeSegmentID = TimeSegment.TimeSegmentID
});
}
Lastly, if you want to display a list of TimeSegments you can do something like this:
[HttpGet]
public ActionResult ListTimeSegments() {
return View(new TimeSegmentsView {
TimeSegments = dc.TimeSegments.ToList()
});
}
And TimeSegmentsView looks like this:
public class TimeSegmentsView {
public IList<TimeSegment> TimeSegments { get; set; }
}
And in the View you'd want to do this:
<table>
<% foreach (TimeSegment TS in Model.TimeSegments) { %>
<tr>
<td><%=TS.Hours%></td>
<td><%=TS.Date%></td>
<td><%=TS.Project.ProjectName%></td>
<td><%=TS.Consultant.ConsultantName%></td>
<td><%=TS.Task.TaskName%></td>
</tr>
<% }; %>
</table>
I hope this is enough to give you a start. It's by no means complete, but its 5 AM and I haven't slept yet, so this will have to do for now (from me). Feel free to name your actions what you want, you don't have to stick to my naming conventions.
I would suggest however that you change the naming of the properties of your tables. For example when your writing the expressions like in the table above you'll have to do TS.Project.ProjectName and that's redundant. You're already accessing the Project property of TS through their relationship so you know you're only going to work with a Project. This then makes ProjectName a pointless blob of text re-describing the object your working with. Instead just use Name, and turn your expression to TS.Project.Name.
Anyway, just a suggestion, do what you like better. I'm passing out, so good night and happy Thanksgiving!
UPDATE
The process with collections is essentially the same as far as the controller side is conserned. It's the client side and the JavaScript that's more difficult to get going, so I'll assume that you have something established on that end.
So, here's how the controller would work. You pass in an array of TimeSegment and the model binder is smart enough to figure it out through the Prefix of your form elements.
<form action="/<%=Model.TimeSegment.TimeSegmentID%>" method="post">
<p>
<label>Hours</label>
<input name="TimeSegment[0].Hours" />
<!-- Notice the array in the prefix -->
</p>
<p>
<label>Hours</label>
<input name="TimeSegment[1].Hours" />
<!-- Notice the array in the prefix -->
</p>
</form>
And the controller:
[HttpPost]
public RedirectToRouteResult CreateTimeSegments(
[Bind(Prefix = "TimeSegment", Include = "Hours,Date,ConsultantID,ProjectID,TaskID")] TimeSegment[] TimeSegments) {
dc.TimeSegments.InsertAllOnSubmit(TimeSegments);
dc.SubmitChanges();
return RedirectToAction("ListTimeSegments");
}
And that's it. Of course you'll want to validate or do other stuff before sending to the database, but that's roughly all there is to it.
UPDATE 2
I believe you can do an IList<TimeSegment> instead of TimeSegment[] without issues, but as far as if it's better, that's up for debate. The way I look at it the browser still sends a virtual array to the server so having the action receive an array feels natural, but its up to you what you want to use.
So, a generic list action would look like this:
[HttpPost]
public RedirectToRouteResult CreateTimeSegments(
[Bind(Prefix = "TimeSegment", Include = "Hours,Date,ConsultantID,ProjectID,TaskID")] IList<TimeSegment> TimeSegments) {
dc.TimeSegments.InsertAllOnSubmit(TimeSegments);
dc.SubmitChanges();
return RedirectToAction("ListTimeSegments");
}
Keep in mind that I haven't used this (meaning the IList) before so I can't guarantee it will work, just speculating...
UPDATE 3
About what you want to do with the Consultant, it sound a lot like what I do with Cookies. I have a BaseView class which is the type used by the Site.Master and then all other views extend from it. In the BaseView I have a Cookie property which is always populated by each controller action. I then use that property to get the id of the currently authorized user.
So, in code it looks like this (using examples from one of my apps):
public class BaseView {
// Don't confuse with an HttpCookie, this is an object in my database...
public Cookie Cookie { get; set;}
}
public class EmployeeView : BaseView {
public Employee Employee { get; set; }
}
And with this, say I want to add a note to an employee, my form would look like this where I pass in a hidden field which is where your ConsultantID comes into play.
<form>
<input type="hidden" name="Note.AuthorId" value="<%=Model.Cookie.EmployeeId%>" />
<!-- other fields -->
</form>
Hope this helps.

Resources