Submit a List from View to Controller - asp.net-mvc

can anyone please show me the code for posting a list on button click from view to controller in mvc3-asp. i have a list in which one of the list element is check box.at first i have to select some of the values from list then submit it to save the selected values only.

Your question is two broad to answer. So i will give you a generic example which you need to customize according to your scenario.
Assuming your view is to assign some tasks to users. Each user can be assigned to one ore more tasks.
So i will create a viewmodel like this.
public class UserViewModel
{
public int UserId { set;get;}
public string Name { set;get;}
public List<Task> Tasks { set;get;}
public UserViewModel()
{
Tasks=new List<UserTask>();
}
}
public class UserTask
{
public int ID { set;get;}
public string Name { set;get;}
public bool IsSelected { set;get;}
}
Now in your GET action, you create an object of UserViewModel and set the Tasks property to a list of available taks (from your database may be)
public ActionResult Add()
{
var vm=new UserViewModel();
vm.Tasks=GetAvailableTasks();
return View(vm);
}
Assuming GetAvailableTasks is a method which returns a list of UserTask objects.
Now create an editor templates. Go to your ~/Views/YourControllerName folder and create a folder called EditorTemplates. Add a new view to the newly created folder and give name as Task.cshtml. Add the below code to that
#model YourNameSpace.UserTask
<p>
#Html.CheckBoxFor(x => x.IsSelected) Model.Name
#Html.HiddenFor(x => x.ID)
</p>
Now go back to your main view and use EditorFor helper method to bring the EditorTemplate.
#model YourNamespace.UserViewModel
<h2>Quiz 24</h2>
#using (Html.BeginForm())
{
#Html.EditorFor(x=>x.Tasks)
<input type="submit" />
}
Now when the form gets submitted, you can get the selected checkbox values like this
[HttpPost]
public ActionResult Save(UserViewModel model)
{
List<int> taskIds=new List<int>();
foreach (var task in model.Tasks)
{
if (task.IsSelected)
{
//you can get the selected task id's here.
taskIds.Add(task.ID);
}
}
//to do : save and redirect (PRG pattern)
}
Here is a blog post explaining how to use EditorTemplates to handle collections on form submit. the post is showing an example to handle radio buttons.

You can actually skip all this rebuilding in the controller. Razor can rebuild the list of any object using a single form. You just need to fallback to the old for and assign a unique name, as well as include the primary key for that collection.
On postback razor will rebuild your ViewModel with the modified list without any extra work.
In the markup it looks something like this
And in the controller after posting back the model is rebuilt with the new data the user has entered, and also lazyBound to ForeignKey models!
Using checkboxes or radio inputs it's slightly different. The problem is that when a checkbox is not ticked, browsers do NOT submit it back, and the model will NOT rebuild. This is not a shortfall of VS but an intended implementation of HTML1 that still lives in HTML5!
If this happens the Index Out of Bounds will occur. So you have include a hidden field for checkboxes with a value of false before the Input Box (if a user checks it it will overwrite the false to true)
But if you are using a StronglyTyped model, like in my case, any check boxes evaluated to null are automatically set to false, known as the default value for a boolean as defined in the C# specification.

Related

How to make DropDownListFor use item IDs instead of indices?

I have a table with a dropdown list in each row, like this:
#Html.DropDownListFor(m => m.Transactions[i].CategoryID, ...)
and everything mostly works. I can select items, submit the form, and the model has my updated selections. So far so good.
The problem is that this isn't very reliable. Since the name of each dropdown is based on an index rather than an ID that means the match-up between the post values and the actual items living in the database are based on indices. Most of the time that works fine, but what if the list of items changes between the time the page loads and the time a user does a postback? The indices have changed, which means the post data won't match up correctly, and bad things happen. OR I've seen the browser incorrectly try to preserve selections in dropdowns between posts, but because the list of items is changing (what may be item #2 now may be item #3 by the time the page is refreshed) and everything is based on indices, the wrong dropdowns get the wrong values.
So basically, how can I force the dropdowns to generate a name and ID that looks more like this:
Transactions_CategoryID_12385652 // 12385652 is the CategoryID
rather than this:
Transactions_4_CategoryID // 4 is the array index
and still have the benefits of automatic binding?
Edit: The second issue I mentioned (input values being restored incorrectly after a refresh) seems to only happen with Firefox. https://bugzilla.mozilla.org/show_bug.cgi?id=46845
You'd have to write your own custom model binder as well as a Html extension to generate the element names in this way, or you could generate the markup manually using Razor.
Is there a particular reason you want need to do it this way? You're almost always following the conventions of the framework unless there's a good reason not to.
You can pass the exact collection you want to the view and bind that to the DropDownFor html helper.
Say you have a Person.
public class Person
{
public int Id { get; set; }
public int Name { get; set; }
}
And you want to add a new person. Create a view model. Create a property in this view model of type SelectList. This select list will hold the collection of the model you want to populate the dropdown list with.
public class PersonViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public SelectList MySelectList { get; set; }
}
Let's say you want the drop down list to hold the Person's Id as the selected value and the Person's name as the text value. You may want to create a second view model to represent that or use an anonymous object. Let's call the collection myCollection. And let's say that the collection is made up of objects that have two properties (and Id and Name property). Now simply pass this view model with a value for MySelectList.
var viewModel = new MyViewModel
{
MySelectList = new SelectList(myCollection, "Id", "Name")
};
In your razor view you can set up the #Html.DropDownListFor like so:
#Html.DropDownListFor(m => m.Id, Model.MySelectList)
In order to pass a select value to the view for the dropdownlist simply use the SelectList constructor overload that allows this value to be passed:
new SelectList(myCollection, "Id", "Name", selectedValue)

MVC sending data from View to Controller

I am quite new to MVC 3.
I know how to send a strongly typed object from a Controller to a View. What I have now, is a View which contains a table/form which consists of that data.
The user can change that data whilst they're are in that View (html page).
When they click on "Save", how do I send the data from the View back to the Controller so that I can update my database.
Do I overload the Controller method so that it accepts a parameter of the model type? Can you please provide some source code.
(Please do not show code of persisting data to a database, I know how to do that part).
Thank you very much for helping me.
I would also prefer using #Html.BeginForm()
I like creating an action method made for my post data. So let's say you have a UserViewModel:
public class UserViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
Then a UserController:
public class UserController
{
[HttpGet]
public ActionResult Edit(int id)
{
// Create your UserViewModel with the passed in Id. Get stuff from the db, etc...
var userViewModel = new UserViewModel();
// ...
return View(userViewModel);
}
[HttpPost]
public ActionResult Edit(UserViewModel userViewModel)
{
// This is the post method. MVC will bind the data from your
// view's form and put that data in the UserViewModel that is sent
// to this method.
// Validate the data and save to the database.
// Redirect to where the user needs to be.
}
}
I'm assuming you have a form in your view already. You'll want to make sure that the form posts the data to the correct action method. In my example, you'd create the form like so:
#model UserViewModel
#using (Html.BeginForm("Edit", "User", FormMethod.Post))
{
#Html.TextBoxFor(m => m.Name)
#Html.HiddenFor(m => m.Id)
}
The key to all this is the model binding that MVC does. Make use of the HTML helpers, like the Html.TextBoxFor I used. Also, you'll notice the top line of the view code I added. The #model tells the view you'll be sending it a UserViewModel. Let the engine do work for you.
Edit: Good call, did that all in Notepad, forgot a HiddenFor for the Id!
In MVC, the act of scraping out data from POST or GET HttpRequests is referred to as Model Binding - there are plenty of SO questions relating to this.
Out of the box, MVC will bind your Get and Post variables based on convention, e.g. a form field with the name 'FormName' will be bound back to a parameter on your controller with the same name.
Model binding also works for objects - MVC will instantiate an object for your controller, and set the properties with the same name as your form.

MVC 3 Model Binding without Key

I have a question about ASP.NET MVC3 model binding. If I have a class I'm trying to use as a model, but I don't want the key put on the page, the model doesn't bind on a POST. Here is an example:
//Data Model
public class MyModel
{
[Key]
public string MyKey {get;set;} //Perhaps this is an ssn that I don't want on the form.
public string MyValueToGet {get;set;} //This is the value I want the user to enter.
}
//Conroller code.
public ViewResult Index()
{
MyModel model = new MyModel{ MyKey = "SecretInfo", MyValueToGet = "" };
return View(new model);
}
public ActionResult Edit(MyModel model)
{
repository.SaveChanges(model)
}
//View code.
#using(Html.BeginForm("Edit", "Home", FormMethod.Post))
{
Enter a value: #Html.EditorFor(m => m.MyValueToGet)
<input type="submit" value="Salve" />
}
So my problem is that model is null when the Edit method is called upon form submission. I can fix this by putting MyKey somewhere on the page (perhaps as a hidden field), but that is unacceptable if it is some sort of sensitive data. Is there a way to solve this problem? I am new to MVC, so I appreciate any help.
Create another unique but otherwise meaningless identifier like an (auto increment int) and use that to bind.
in other words modify your model to something like:
public class MyModel
{
[Key]
public int ID {get; set;}
public string MyKey {get;set;} //Now this can be sensitive, it doesn't matter because you no longer rely on it.
public string MyValueToGet {get;set;} //This is the value I want the user to enter.
}
EDIT
I believe your best choice would be to change the MyModel object, as it's design is flawed. The primary key in the majority of cases (and I think this is one of them) should be a simple auto incrementing integer, meaningless apart from it's role as the table's key.
While Luke's suggestion to use Session is a viable option and a solution that would work, I would personally do something similar to what I'll explain here, as it would seem to me to be more of the 'mvc way' of doing things.
Data model:
Either change your current model to something like what I suggest above, or, if that is not feasible for whatever reason (breaking dependancies or FK relationships), create a new table that can be used as a join, or proxy, if you will:
public class Proxy
{
public int ProxyId {get;set;}
public MyModel MyModel {get; set;}
}
Obviously, you'd have to do some work to populate this table, but you would then be able to use it to fetch records from MyModel without accessing the MyKey property directly.
It's not considered good practice to use your data models directly in your views, so you want to create a view model as well
public class MyModelViewModel
{
public int ModelId {get; set;}
public string ModelValueToGet {get; set;}
}
Notice we don't even need the key containing sensitive data in the view model.
Then type your view to the viewModel, not the data model, and include a hidden field for the ModelId
#using(Html.BeginForm("Edit", "Home", FormMethod.Post))
{
Enter a value: #Html.EditorFor(m => m.ModelValueToGet)
#Html.HiddenFor(m => m.ModelId)
<input type="submit" value="Save" />
}
Now in your controller you have your get method
public ViewResult Index()
{
//fetch the users record from the database
//if you're using the Proxy table, you'll want to write a LINQ query here
//instantiate a viewModel and populate it's properties using the fetched record
//remember, the viewModel.ModelId should be set to MyModel.ID or Proxy.ProxyId
//render the view
}
And the post method
public ViewResult Edit (MyModelViewModel viewModel)
{
//fetch the users record from the database using viewModel.ModelId
//If you're using the proxy table, you'll need to use that LINQ query again here
//update the record you fetched with the new data the user just entered
//you have complete control here of what gets updated and what stays the same
//pass the updated record to the repository to save the changes.
//redirect the user to be on their merry way
}
I think that's about as well as I can lay it out. Hope it makes sense.
An alternative is to encrypt the id before sending it to the client. Check this post for more information on how to accomplish this.
Asp MVC 3: Modifiy Values Sent to View

mvc.net how to edit member list variables

Given the following model which has a name, url, and an arbitrary list of keywords (I want the user to add a series of keywords) ...
public class Picture
{
public Picture()
{
keywords = new List<string>();
}
public string name {get;set:}
public string url {get;set;}
public List<string> keywords{get;set;}
}
... and the following action in my controller ...
[HttpPost]
public ActionResult Edit(FormCollection fc)
{
if (ModelState.IsValid)
{
// do stuff
}
return View(ModelManager.Picture);
}
In the FormCollection I have the following field
fc["keywords"] = "keyword1,keyword2,keyword3"
And I then create a Picture object based on the form collection.
However, I would prefer to use a strongly-typed action such as
[HttpPost]
public ActionResult Edit(Picture p)
But in this approach, my p.keywords property is always empty. Is there some way to help the framework recreate my p.keywords property before it hits my controller's action method?
I thought an Editor Template might work here, but I don't think there is a way to model bind a nested IEnumerable view model member. Your fastest bet may be handling it directly with FormCollection and some string parsing magic. Otherwise, if you have to strongly-type this, maybe a custom model binder like this could help if you can control your keyword element id's:
public class PictureKeywordBinder : IModelBinder
{
public object GetValue(ControllerContext controllerContext,
string modelName, Type modelType,
ModelStateDictionary modelState)
{
Picture picture = new Picture();
//set name, url, other paramaters here
foreach(var item in Request.Form.Keys)
{
if (item.StartsWith("keyword"))
{
picture.keywords.Add(Request.Form[item]);
}
}
//add any errors to model here
return picture;
}
}
Maybe the keyword id's could be setup in a partial view passed the sub model from your parent view:
<% Html.RenderPartial("PictureKeywords", Model.keywords);
Are your keywords seperate text boxes? If so, create an inputs like this and they will be populated by the model binder.
<input name="keywords[0]" type="text">
<input name="keywords[1]" type="text">
<input name="keywords[2]" type="text">
The way I got around this, is to use a hidden input to store the csv string of items, in your case, keywords.
I then hooked into the form submit event (using jQuery) and appended the inputs to form the csv string, which is then stored in the hidden input. This hidden input was strongly typed to a property on my model.
It's a little clunky, but if you have a dynamic number of possible keywords then this works quite well (except if JS is disabled of course)
In what way you are expecting the user to add more keywords? In the form comma separated values(CSV) or by dynamically adding textboxes?
Based on your requirement, i have two solutions with me.

Storing state in asp.net MVC

I'm building an asp.net MVC 2 app.
I have a list view which lists items based on a parameter. In the database I have a parent and child table, so my list view lists all the child records for where the parent's id matches the value specified in the parameter.
This is my controller and model:
public ActionResult List(int ParentID)
{
return View(new Models.ChildListModel(ParentID));
}
public class ChildListModel
{
public int ParentID {get;set;}
public ManagementUserListModel(int iParentID)
{
this.ParentID = iParentID;
this.Children = DataAccessLayer.ListChildrenForParent(iParentID);
}
public List<Child> Children {get;set;}
}
I also have a details and create action for that controller. The details and create view have a "back to list" action, which I want to go back to the list view, and maintain the original ParentID. So far I've been doing this by creating a hidden field called ParentID in the list, edit, create and details views, so that the model's ParentID property will get populated correctly:
<%= Html.HiddenFor(model => model.ParentID) %>
Then in the "Back to List" action in each view I pass the ParentID:
<%=Html.ActionLink("Back to List", "List", new {ParentID = Model.ParentID}) %>
This all works, but I'm not a big fan of storing raw IDs in the html. Are there any better ways to do this? Is there some built in way to encrypt the data (kind of like the standard asp.net viewstate did?) I'm just trying to achieve some sort of tamper resistance, and trying to avoid using session state (TempData, etc) because I don't want to have to handle session timeouts.
You may take a look at this article. You could use the new Html.Serialize extension method in your view which allows you to serialize entire objects and encrypt it:
<%= Html.Serialize("person", Model, SerializationMode.Encrypted) %>
Which serializes the Model into a hidden field and encrypts the value. To get the model back you use the DeserializeAttribute in the controller action to which the form is submitted:
public ActionResult Edit([Deserialize]Person person) { }
Another way to do this that doesn't expose the id and also doesn't add to the weight of the subsequent form post (like Webform's ViewState does and Html.Serialize would) is to use the session as the backing store inside your Model class.
public class ChildListModel
{
public int ParentID {
get
{
return (int)HttpContext.Current.Session["ChildListModel.ParentID"];
}
set
{
HttpContext.Current.Session["ChildListModel.ParentID"] = value;
}
}
public ManagementUserListModel(int iParentID)
{
this.ParentID = iParentID;
this.Children = DataAccessLayer.ListChildrenForParent(iParentID);
}
public List<Child> Children {get;set;}
}
If you like, you could even store the entire Parent object in your model that way instead of just it's ID - that would add to the session size on the server which may or may not be desirable (depending on how long your session lasts and whether it is set to be stored in memory or in sql server, etc.)
The easiest way would be to keep the parentid in the URL. It will look a bit strange for the Create Action but I still think that this the less troublesome way.
If you keep state, you will alwas have the problem that you can not hit F5 and you can not bookmark the page.
The backlink is a simple ActionLink in this case.
Urls would be:
/YourController/List/YourParentParameterValue
/YourController/Detail/YourParentParameterValue/YourDetailParameterValue
/YourController/Create/YourParentParameterValue

Resources