Get all textboxes' values in a form in MVC3? - asp.net

I have a form tha contains a TreeView with many Textboxes in each node. the TreeView created dynamically with Razor and I don't know the name or ID of textboxes.
How can I get the value and id of all textboxes in the controller in MVC3 ?

I would use the FormCollection class. Read about it here http://msdn.microsoft.com/en-us/library/system.web.mvc.formcollection.aspx
In your controller;
Public ActionResult ActionName(FormCollection formCollection){
}
This allows you to gain access to any of the keys posted.

Request.Form.AllKeys will allow you to access all the fields in the form's ids. Then you can use Request.Form[id] to access the value.
Edit: Possible Dupe:How can I get all element values from Request.Form without specifying exactly which one with .GetValues(“ElementIdName”)

Related

Problem with one controller handling two forms (models)

I have to implement this form, which at first seemed easy to me. For the models part, I created a one-to-many relationship between GeneralInformation and CourseList (very obvious). In the GeneralInformation I included the bottom section as well with the 'Comments', 'Remarks'etc.
The problem is that before submitting the General Information section, you fill the Course List which will give an error for the FK constraint (again, obvious). For the Course List I'm using DevExtreme datagrid.
The only solution I came up with is to create another table, which keeps the ID of GeneralInformation and each Course ID. A similar solution for many-to-many relationships. If this seems like a viable solution, then how do you store the IDs of Courses in the controller, and then the ID of GeneralInformation, to put them in the database. Now I think I'm handling two models with the same controller, which might not be an optimal solution or even against guidelines of .NET Core.
If someone has a better solution, it would be greatly appreciated.
Your Model can be like this
public class Model_Name //enter your model name
{
public string FirstName {get;set;}
public string LastName {get;set;}
//other properties from General Information form
public List<Course> Courses {get;set;} //Course is a separate model
public string Remarks {get;set;}
}
In HTML do not map course to General info, Post the form and pass all the fields as json like below
{'FirstName':'Test','LastName':'Test','Courses':[{'Id':1}], 'Remarks':'test'}
So you're basically asking how to bind to a collection in a model.
Property binding would look like this:
<input asp-for="#Model.Collection[i].Property" />
What i did was store the course table (or grid) row as a partial view that takes an index as an argument with the course model and at the same time i maintain an index of the courses count using data-id attribute on each row and then every time a user wants to add a course i use ajax with the index of the last course as a parameter to fetch a new row rendered with an incremented index
and i append it to the table.
That way when your submit your form it will bind to a collection what ever the length is.

Autogenerated form in asp.net MVC3

Depending multiple choices done by a user in few steps I have to generate a form in a web page for the user.
In a database I had all the necessary stuff (regex validation of every form field, name, type etc.) I would like to know what could be the best way to autogenerate a form using MVC3.
Should I autogenerate a model, set the model of my views to dynamic, and inject some validation attributes to every property of my dynamic model?
How should I get the values on my post action?
As the fields are all dynamic (from the database), your model could very easily store an IEnumerable where Question is an object which has information about the type of field. i.e. Id, TypeId (text, checkbox, select list), Wording, Heading, ValidationTypeId etc.
Then use mvchelpers passing in Question to a method which would determine the html to output. This could very well include a validator.
On the form loop over Model.SurveyQuestions and for each row send Question to the mvc helper. The helper, knowing everything about the Question can output the label, type of input box and the required validator.
This is a wise way to accomplish what you are trying to do as your input fields is dynamic. I just completed a project doing exactly this.

EntityDataSource repeats the first record instead of returning different records?

I have an ASP.NET web application which uses EF4. I have a page with an EntityDataSource that filters records from a SQL Server view. There is a GridView bound to my EntityDataSource to display the view records.
I've used this approach on many pages where the EntitySet associated with the EntityDataSource is linked to a SQL server table. I'm trying now for the first time to use an EntitySet that is bound to a SQL view.
The EntityDataSource returns the correct number of rows, depending on the where clause parameters.
However, each row returned from the EntityDataSource is exactly the same.
I've debugged the GridView's RowDataBound event and confirmed that every row being bound has exactly the same content each time.
Something that is interesting is that when you page back or forth, the record being repeated changes. I'm guessing that somehow the first (or last?) record in any given page is the one that's being repeated.
This feels like a bug in EF or the EntityDataSource. Has anyone seen this kind of behaviour before or do you have any advice around how to troubleshoot it?
I've seen this happen in other scenarios when the entity's key property(ies) that come back from the view are not unique. EF will end up only materializing a single entity and thus the problem.
Are you sure the properties marked as entity keys are unique within the view?
Jeff answer completly true , i want say a solution for some body have no unique key in their model,
maybe you select a view that has no unique key then you can add column as like as [RowNumber] that can be unique and dont forgett add it to your view model with [Key] Property as like as this :
[Key]
public int Row { get; set; }

How to read input value from the Request.Form collection by input name

I want to be able to read values of HtmlHiddenField controls from the Request.Form collection in a user control on postback. The keys in the collection seem to represent the control's name attribute rather than ID. I can control the ID using the new ClientIDMode property which helps when my user control is placed in different pages thus within different naming containers. But how can I do the same with the name attribute? The HtmlHiddenField.Name property doesn't match the key name in Reqest[key] object when in a naming control.
I understand this is quite specific scenario because I don't have access to the hidden field control object. I am just looking for a way to control how the input name attribute is rendered as is now possible for IDs.
You will have to access the value of the hidden field using the unique id property of the control like below
var postedValue = Request.Forms[hdnField.UniqueId];

Make Gridview interact with something other than properties

We're planning to create a web application where users can build custom "forms," choosing which fields they would like, and how the data in those fields should be represented. Users can then fill out these forms in a DetailsView-like control, thereby creating "documents." The documents can be shown in a DetailsView, or certain fields of several of them can be shown in a GridView. At least, that's the idea.
The problem is that GridView and DetailsView seem to be specifically designed to access Properties on objects that come out of a DataSource. Since we want to have completely arbitrary forms, we can't restrict ourselves to building a class with Properties to represent each field. We have to be able to have any number of dynamically-specified fields on a form.
Is there any way to leverage the existing controls so we don't have to re-implement paging, sorting, and all the other things that GridViews are already set up to do, or will I just have to create my own GridView-like control from scratch?
Edit:
More specifically, the difficulty I am having is in getting inline editing to work on the GridView. For example, let's say that one of the "fields" that is added to a "form" is a calendar field, which should display a date as text in read-only mode, and display a calendar control in edit mode. When the "save" button is clicked, the date selected by the calendar control needs to be saved to the database as the new value for the given field of the given document (i.e. instance of the form). My initial idea was to create a special DataControlField class which, given a form field key, would know how to databind thusly:
FormDocument doc = DataBinder.GetDataItem(cell) as FormDocument;
FormFieldValue fieldValue = doc.FieldValues[FieldKey];
fieldValue.AddReadOnlyControls(cell);
... instead of:
Object dataObject = DataBinder.GetDataItem(cell);
cell.Text = DataBinder.GetPropertyValue(dataItem, FieldKey);
This would probably work for displaying the field values, but if the user tries to edit and save one of the FormDocuments I don't know how I would convince the GridView to do something like this:
doc.FieldValues[FieldKey] = newValue;
Currently, the API for DataControlField uses the ExtractValuesFromCell method to put the property name and value into an IOrderedDictionary. Those values are then applied to the given properties of the objects in the GridView's databound IEnumerable. The problem is, I can't work with properties of an object because in this case the object needs to have a completely arbitrary number of fields.
A GridView can be bound to any object that implements IEnumerable. The advantage of using one of the xDataSource controls is that it can implement paging and sorting for you without any additional code, but you certainly aren't tied to them.
If I understand your question correctly, you do not know the number of columns to display in the GridView until runtime. In that case, I would recommend building an array from your form data and binding the grid to that. You will have to implement paging and sorting yourself.
The DetailsView is not very customizable so you should take a look at the FormView. However, I think you are going to end up dynamically adding controls to whatever container you use.
What you need is totally dynamic GridView. I quess you would have to extend it with the controls ( functionalities ) in your description
Here's what I ended up doing:
I created a new data type that contained a Dictionary of answers, indexed by Field ID.
I created a new type of DataControlField with a FieldId property, which retrieves the proper answer value for that FieldId from the Dictionary mentioned above.
I added data type and data keys properties to this custom DataControlField and overrode the ExtractValuesFromCell method so that it could create a new instance of the answer class and add those values to a Dictionary, which was stored under the property name by which that dictionary would be found in the new data type mentioned in step 1.
I used my own GridView class, used the .NET Reflector to see how the normal GridView calls the ExtractValuesFromCell method, and then changed that so that it would pass the same Dictionary object in to each DataControlField. This way, each field could add to the same Dictionary, rather than replacing the Dictionary that the last one had added under the same property name.
I used a DataFieldGenerator to generate the one of my custom DataControlFields for every field associated with a given form, and I told the GridView to use that DataFieldGenerator to auto-generate its fields.
I set up my ObjectDataSource so that it would know how to save all the answer values from an object of the type mentioned in step 1.
It was tricky, but worthwhile.

Resources