I need to add dynamic controls in MVC that I have done through view but I am facing problem in inserting records. My query is there are pre-defined questions based on that answertext boxes will be generating. So each question should display corresponding to its answer.
If there are 20 questions then at run time it will generate 20 answer text boxes which means multiple records are going at once. As far as I know I will do it through DataTable please correct me if I am wrong. But how would I send data through view I am able to perform get request but unable to send multiple records and repository file as well.
Following is my schema
tblAnswer
AnswerID identity column primary key,
AnswerText varchar(500)
QuestionId foreign key
tblQuestion
QuestionId primary key identity column
QuestionText
for instance:-
#foreach(var ques in Models.questions)//questions is a list of questions
{
//enter code here
#ques.QuestionText ///will display question text
#Html.TextboxFor(model=>model.AnswerText)
<br/>
}
If i take list above then it will force me to take model[i], AnswerText then I need to pass list though I am passing list still not able to perform.
Model
public int AnswerId,
public string selectedAnswer,
public int AnswerText,
public int QuestionId,
public list<Question> questions
Selected answer is in radio button there would be 10 radio button on the screen which is also associated with other table. And questiontext does not exist in Answer table
I would handle this by creating a custom ViewModel that contained a string for the question and a string for the answer entered, then return a collection of these to bind to your view.
Related
I have two classes say Author and Book.
I show you simplified code here
class Author
{
int Id
string Name
virtual ICollection<Book> Books;
}
class Book
{
int Id
int AuthorId
string Name
bool Flag
}
In one of my views, I want to edit Author but when saving the object, I want to update some of his books and set the Flag to true;
My save method looks like this
public ActionResult SaveAuthor(Author data)
{
// call Web API to save Author and also update Flag for some of the data.Books.
// but data.Books is empty at this point.
}
In this method, the data parameter, includes author information but, it does not include the Books information so data.Books is empty. The reason is I don't have Books information in my View and View does not bind the Books information.
My question is how I can populate the Books collection inside SaveAuthor method or preferably inside Web API which saves the author.
One answer is I should include all books (as hidden field) for the author in view so I can get it back in data parameter.
Is there any other way achieve this goal without adding Books into View?
I'm using VS 2015 and probably MVC4
This question already has an answer here:
Submit same Partial View called multiple times data to controller?
(1 answer)
Closed 4 years ago.
I struggled a lot with this today, I hope this post helps other people
The case
I have a form, which must contain dynamic amount of fields, depending on user input. The model for this form is Contest:
public int NumberOfRounds { get; set; }
public List<Round> Rounds { get; set; }
Round model looks like this:
public int Length { get; set; }
NumberOfRounds field indicates the amount of Rounds a Contest contains. I use a simple js script with "change" event listener to add additional input fields, according to the value of NumberOfRounds entered by the user.
The question is how to bind those input fields to my Contest model, in order to get their values in inside the Round.Length property.
The key is in the name attribute of the HTML tag. At the top of my View, I have defined #model Contest. This sets the context of the View to the Contest object. Now we can use name attribute to bind an input value to the corresponding model property.
I recommend this article as a good read on Model binding to a List property. Also this topic for more specific information.
In our case however we have a List<Round> Rounds property. How do we bind individual inputs to each Round.Length. Its simply:
<input ... name="Rounds[{index}].Length"
Where {index} is the position at the Rounds list, at which to save the current input's value. True, it is simple enough, but I think a clear example of the issue would be very useful for newcomers. Hope it helps :)
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)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need to write a mobile Web application (MVC), where I have been given the UI Design that I need to work to and I am not sure of the best approach and was looking for any recommendations.
To simplify the project:
The 1st view asks for a number
The 2nd view asks for a category
Based on the logic of the first two values, I can show up to 6 different forms/views each collecting different data pieces.
This data then gets written to a single SQL table
I am not sure if I should:
Have one controller and one model, and I just keep track of which View needs to be shown within that controller
OR
Have mutiple models, each based on a previous model
OR
Use panels (ie. used to this with WebForms), and make these panels visible again based on tracking which section needed to be viewed.
Any advice would be appreciated,
Mark
It all depends on the Models.
Case 1:
There's only going to be one database table (i.e. one survey)
If there's going to be only one database table, you'll only need one controller and one View.
For example:
public class Survey
{
public String Answer1 { get; set; }
public String Answer2 { get; set; }
public String Answer3 { get; set; }
}
The view can ask the first questions, and accordingly display the appropriate fields. So only the final Submit button will be a HTTP Post. All the previous buttons will just perform a simple JavaScript action.
Case 2:
The first questions are used to decide which survey the user should take.
I'll have an Action that returns an intial View. The view does a HttpPost to another Action (ShowSurvey)
public ActionResult Index()
{
return View();
}
[HttpPost]
public async Task<ActionResult> ShowSurvey(string id)
{
switch(id)
{
// display the appropriate View here.
}
}
ShowSurvey would that take a parameter using which you know which survey you're supposed to display. This action will have it's own View/View(s). (One view if all the survey questions are similar. Else you might need to have more views).
This would be my approach BTW. Critics are welcome!
UPDATE:
I read your question again and you've mentioned you've got only one SQL Table. So yeah Case 1 will be the easiest way.
Display the initial questions. Decide what to show etc. at runtime using JavaScript. Once the user has finished answering all the questions, you can show him (or enable) the Submit button that'll perform a HTTP Post back to your action and commit the data to the Database.
PS: I've used the word survey just because questions remind me of them :P
The question is how these two are related? Is the value entered into the first field have influence on the second? I'd build some simple two field model or - since I like pass to view explicit structures, I would add another field to the model containing list of available options, so it would be:
public class MySimpleModel{
public int MyNumber{get; set;}
public string MyCategory{get; set;}
public List<string> Categories{get; set;}
}
and then post it controller (by regular form submit or ajax):
public class MyController:Controller{
[HttpGet]
public ActionResult Index(){
return View();
}
[HttpPost]
public ActionResult Index(MySimpleModel model){
if(model==null)
return Index();
if (model.MyNumber>3 && model.MyCategory=="xxx")
return View("View1",model);
//etc.
}
}
About user interface - make it user friendly and logical. You didn't wrote anything about requirements, so it's hard do advise you :)
I want to create a form where the user creates a list and then saves it. The list can have an arbitrary number of rows. The user cannot save the list until it is complete (all rows/items are added) and I cannot use javascript to do it all on the clientside before posting.
The form will create a contact, like in an address book or something. The entity looks like this:
public class Contact
{
public string Name { get; set; }
public string Company { get; set; }
public List<ContactRow> ContactRows { get; set; }
}
The ContactRow looks like this:
public class ContactRow
{
public string Type { get; set; }
public string Value { get; set; }
}
So, basically it is a contact with a name and a company. The contact has a list of contact rows, where each row has a type (phone, email, etc) and a value (555 - 12334, test#email.com, etc).
My form will contain two ordinary textboxes for Name och Company respectively. But I'm not sure how to handle the list with contact rows. What I want the user to be able to do is adding new rows, editing rows and deleting rows. All this must be done before the save button i clicked, i.e. the list must be all done when saving.
This is not very hard to to with javascript and I've already done that. But now I want to implement this functionality without javascript. It is ok to post to the server while building up the list, but the list cannot be saved until it is done.
Ideas?
If you do not wish to use javascript a postback whilst building up the list is all you can do.
This user experience is often deemed poor as work is ongoing, but is the best starting point when using progressive-enhancement to make your application more user friendly.
The OP stated Javascript was not an option. I feel your pain as one of our applications had a similar requirement. We have a construct called an updateable list with the same functionality as you outlined.
We perform data handling on the server. Each list is displayed in a table. Each row contains the item data and has an action icon associated with it. The default is to display and we support new, updated and deleted actions.
After the user enters data for an item they press a button to add or remove the item from the list. Selecting existing items allows for an update operation. The list, and status, is determined on the server and the client does not run Javascript.
As #rich.kelly pointed out you will need to go to the server for each operation. It takes longer to do anything and your session gets a workout but it meets the client requirements.