ASP MVC 3 controller action not receiving all the parameters - c#

So I have a view similar to this:
...
<input type="text" id="FieldOne" />
<input type="text" id="FieldTwo" />
<input type="text" id="FieldThree" />
...
That mimics this class:
public class Foo{
public string FieldOne { get; set; }
public string FieldTwo { get; set; }
public string FieldThree { get; set; }
}
And an action in the corresponding controller:
[HttpPost]
public ActionResult View(Foo param)
{
...
}
When I submit the form, the parameter "param" in the Post action properly copies the values of all the fields that match the class, except for one of them (say, FieldOne). These inputs are generated by Html.TextboxFor().
Is this a idiosyncratic problem or is there something I may be forgetting about?

Your input boxes are not valid. They should look as follows:
// Start Form
<input type="text" id="FieldOne" name="FieldOne" />
<input type="text" id="FieldTwo" name="FieldTwo" />
<input type="text" id="FieldThree" name="FieldThree" />
// End Form
With that said is there any reason why you are not using the Html Helpers? Given your model it would be better to write your form as follows:
// Start Form
#Html.TextBoxFor(m => m.FieldOne)
#Html.TextBoxFor(m => m.FieldTwo)
#Html.TextBoxFor(m => m.FieldThree)
// End Form

Related

How to bind list<object> to a model and submit along with other form data?

This is what I'm trying to do:
I have a form with some input fields. Part of the form allows user to choose multiple options (Books) but will not know how many.
Model:
public class Data
{
public string name { get; set; }
public string age { get; set; }
...
public List<Books> books { get; set; }
...
}
And,
public class Books
{
public string Title { get; set; }
public string Author { get; set; }
}
View:
#model Applicants.Models.Data
...
<input type="text" name="Title" value="" />
<input type="text" name="Author" value="" />
My question is, how do I submit multiple titles and authors along with other form data? And how to properly name the input fields?
I have read this https://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/
But the example only submitted a List, not with other data.
Thanks.
Since you're using Razor view, you can use strongly-typed #Html.TextBoxFor() helpers and use for loop to generate multiple textboxes inside books list:
#model Applicants.Models.Data
#using (Html.BeginForm())
{
#Html.TextBoxFor(model => model.name)
#Html.TextBoxFor(model => model.age)
#for (int i = 0; i < Model.books.Count; i++)
{
#Html.TextBoxFor(model => model.books[i].Title)
#Html.TextBoxFor(model => model.books[i].Author)
}
#* don't forget to add submit button here *#
}
The loop will produce <input> elements like this example below, assumed that you have POST action which has Applicants.Models.Data as viewmodel parameter:
<input name="books[0].Title" type="text" value="sometitle">
<input name="books[0].Author" type="text" value="somevalue">
<input name="books[1].Title" type="text" value="sometitle">
<input name="books[1].Author" type="text" value="somevalue">
<!-- other input elements depending on books list count -->
Refer to this fiddle for working example.
you can do like this for bind model for normal html syntax its just example
you need modified according to your need
<input type="text" name="Model.name" value="Curious George" />
<input type="text" name="Model.age" value="H.A. Rey" />
<input type="text" name="Model.books[0].Title" value="Curious George" />
<input type="text" name="Model.books[0].Author" value="H.A. Rey" />

Posting a list of complex objects in MVC with Razor

SCENARIO:
First of all, sorry for my english.
What I'm trying to do is posting trough form-POST the following object:
public class AppConfigViewModelInput
{
public string Setting { get; set; }
public string Value { get; set; }
}
to the following method:
[HttpPost]
public ActionResult Index(List<AppConfigViewModelInput> listOfAppConfigToUpdate)
{ ... }
But this input-object is constructed by only two properties of the view-object that I use to show the data on my razor page:
public class AppConfigViewModel : AppConfigViewModelInput
{
public string Description { get; set; }
public string ConfigType { get; set; }
public int ViewOrderInWebAdmin { get; set; }
public string ViewSpecialBackgroundColor { get; set; }
}
I was reading a lot of questions and blogs (check out SO References in the question). Finally I could get the following code for my razor page (I only post the form-code section):
#model List<PGWebAdmin.Models.AppConfigViewModel>
#{
var itemCnt = 0;
}
#foreach (var item in Model)
{
itemCnt++;
<input type="hidden" name="AppConfigViewModelInput.Index" value="#itemCnt" />
<input type="text" class="input-sm form-control" value="#item.Value" name="AppConfigViewModelInput[#itemCnt].Value"/>
<input type="text" name="AppConfigViewModelInput[#itemCnt].Setting" value="#item.Setting"/>
}
and the form is created by:
#using (Html.BeginForm("Index", "AppConfig",
FormMethod.Post, new { #class = "navbar-form navbar-right", role = "search" }))
{
QUESTION:
I could send the data, I'm checking with the dev tool the following information:
that is posted to the method, and the method is hit, but the value of the parameter is null:
I tested and corrected and tried several ways to do this but this is the far away I could get, and I can't understand what's happening.
I'm doing something wrong? Why I'm still getting null?
Any help will be preciated.
Thanks!
REFERENCES:
MVC post a list of complex objects
How can I post a list of items in MVC
Posting to a list<modeltype> MVC3
You need the change the name of the parameter to match what you are sending in the "name" field.
ie change your post controller:
[HttpPost]
public ActionResult Index(List<AppConfigViewModelInput> AppConfigViewModelInput)
{ ... }
Try this? It's maybe not the best answer but it should work for your purposes.
[HttpPost]
public ActionResult Index(AppConfigViewModelInput[] listOfAppConfigToUpdate)
{ ... }
And the html like this ..
#model List<PGWebAdmin.Models.AppConfigViewModel>
#{
var itemCnt = 0;
}
#foreach (var item in Model)
{
itemCnt++;
<input type="text" class="input-sm form-control" value="#item.Value" name="listOfAppConfigToUpdate[#itemCnt].Value"/>
<input type="text" name="listOfAppConfigToUpdate[#itemCnt].Setting" value="#item.Setting"/>
}
I removed the top input of index.. i don't see where it fits in. You can convert the array to a list inside your Index method.
I dont see the reason you send the AppConfigModelInput.Index, i think that might be your problem. The message you send should not contain data that is not part of the model
Your input file names are wrong ! Since your HttpPost action expects a collection of AppConfigViewModel. You don't really need the AppConfigViewModelInput. prefix for your input field names. For model binding to work, Your input field names should be like
<input type="hidden" name="[0].Index" value="" />
<input type="hidden" name="[1].Index" value=" />
Also make sure your form elements are in a form tag.
The below should work.
#model List<PGWebAdmin.Models.AppConfigViewModel>
#{
var itemCnt = 0;
}
#using (Html.BeginForm())
{
foreach (var item in Model)
{
<input type="hidden" name="[#itemCnt].Index" value="#itemCnt" />
<input type="text" value="#item.Value" name="AppConfigViewModelInput[#itemCnt].Value"/>
<input type="text" name="[#itemCnt].Setting" value="#item.Setting"/>
itemCnt++;
}
<input type="submit" value="Save" class="btn btn-default" />
}

Can't insert the selected value of CheckBox to database, it never hits my post submitData method

My controller I cant seem to bind the submitdata method to check box with id=answerA. At the moment I just want to insert one value the later will adjust accommodate 3 answer options:
[HttpPost]
public ActionResult SubmitData(QuestionnareModels models)
{
using (QUESTIONNAREDataContext db = new QUESTIONNAREDataContext())
{
SubmitTable answerSubmit = new SubmitTable()
{
SubmitID = 1,
CorrectAnswer = models.AnswerA
};
db.SubmitTables.InsertOnSubmit(answerSubmit);
db.SubmitChanges();
}
return RedirectToAction("Index");
}`
My view, where I render my check boxes from a linq database:
<div class="container">
<h2><mark>Questionnare system</mark></h2>
#using (Html.BeginForm("uploadAnswer"))
{
foreach (var questionType in Model)
{
#questionType.Question
<br/>
<br/>
<input type="checkBox" id="AnswerA" />
#questionType.AnswerA
<br />
<input type="checkBox" id="AnswerB" />
#questionType.AnswerB
<br />
<input type="checkBox" id="AnswerC" />
#questionType.Answerc
<br/>
<br/>
}
<br />
<button type="submit" class="btn btn-success" id="submitDataButton">Submit</button>
}
</div>
Your code has multiple problems including invalid html (duplicate id attributes), missing name attributes (nothing in the form will post back), incorrect use of checkboxes (unchecked checkboxes do not post back so there is no way of knowing which answer belongs with which question), posting back to the wrong method and allowing multiple answers for the same question. You need to create view models that represent what you want to display and edit
View models
public class QuestionVM
{
public int ID { get; set; }
public string Text { get; set; }
public int SelectedAnswer { get; set; }
public List<AnswerVM> AnswerList { get; set; }
}
public class AnswerVM
{
public int ID { get; set; }
public string Text { get; set; }
}
Controller
public ActionResult Create()
{
List<QuestionVM> model = new QuestionVM();
// populate your questions and the possible answers for each question
return View(model);
}
[HttpPost]
public ActionResult Create(List<QuestionVM> model)
{
// The model now contains the ID of each question and the ID of its selected answer
}
View
#model List<QuestionVM>
#using(Html.BeginForm())
{
for(int i = 0; i < Model.Count; i++)
{
#Html.HiddenFor(m => m[i].ID)
#Html.DisplayFor(m => m[i].Text)
foreach(AnswerVM answer in Model[i].AnswerList)
{
string id = "answer" + answer.ID;
#Html.RadioButtonFor(m => m[i].SelectedAnswer, answer.ID, new { id = #id })
<label for="#id">#answer.Text</label>
}
}
<input type="submit" value="Save" />
}
Looking at you controller code, I suspect your database structure is wrong. You would need a table for Questions (ID, Text, etc), a table for Answers (ID, Text, QuestionID, etc) and a table for users answers to questions (say) UserQuestionaires (UserID, QuestionID, AnswerID, etc)
<div class="container">
<h2><mark>Questionnare system</mark></h2>
#using (Html.BeginForm("SubmitData"))
{
foreach (var questionType in Model)
{
#questionType.Question
<br/>
<br/>
<input type="checkBox" name="AnswerA" />
#questionType.AnswerA
<br />
<input type="checkBox" name="AnswerB" />
#questionType.AnswerB
<br />
<input type="checkBox" name="AnswerC" />
#questionType.Answerc
<br/>
<br/>
<button type="submit" class="btn btn-success" id="submitDataButton">Submit</button>
}
<br />
}
</div>
Two issue
BeginForm should have method or action you have specificed in Controller
Submit button must be inside form.
You should not use ID. You have to use name.
If i understand your problem, I can see the 'form' action in html is "uploadAnswer" where as you posted the action method code for "SubmitData".
So what happens if you change "uploadAnswer" in Html.BeginForm("uploadAnswer") to Html.BeginForm("SubmitData"), are you able to hit the controller ?
Also for proper model binding, the name of html element and the property name of model should be same. So change html to: <input type="checkBox" name="AnswerA" id="AnswerA" /> (Assuming "AnswerA" is a property of your Questionaire model.
If you want to model bind to a collection, please take a look at here and here.

Filling model list property in mvc

I have a model with a list property. In my view the user will fill in a fixed number of similar data (name number etc). How can I collect that information and create a list of it on the post? Thanks for any help.
public class mainonject
{
public List<test> list{ get; set; }
}
public class test
{
string name;
string number;
}
<form>
HOW DO I COLLECT THE PROPERTY list AS A LIST TO THE SERVER
<input type="submit" value="submit"/>
</form>
Just add the fields to your form and use the right indexes in there name properties:
<input name="list[0].Name" type="text" />
<input name="list[0].Number" type="text" />
<input name="list[1].Name" type="text" />
<input name="list[1].Number" type="text" />
...

do a HTTPPOST MVC2

I have a MVC2-application. in this application I have a strongtyped view contending the modell NewHorseModel:
public class NewHorseModel
{
public List<Category> Faehigkeit { get; set; }
}
public class Choice
{
public int Id { get; set; }
public string Name { get; set; }
public string Beschreibung { get; set; }
public bool Selected { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string Beschreibung { get; set; }
public List<Category> Subcategories { get; set; }
public List<Choice> Choices { get; set; }
public int Parent { get; set; }
}
The View looks like this:
<p>
<input faehigkeit_ID="1" id="Selected" name="Selected" type="checkbox" value="true" />
<input name="Selected" type="hidden" value="false" />
Mitteltrab
<input id="Id" name="Id" type="hidden" value="1" />
</p>
<p>
<input faehigkeit_ID="2" id="Selected" name="Selected" type="checkbox" value="true" />
<input name="Selected" type="hidden" value="false" />
Arbeitstrab
<input id="Id" name="Id" type="hidden" value="2" />
</p>
<p>
<input faehigkeit_ID="3" id="Selected" name="Selected" type="checkbox" value="true" />
<input name="Selected" type="hidden" value="false" />
Trab versammelt
<input id="Id" name="Id" type="hidden" value="3" />
</p>
<p>
<input faehigkeit_ID="11" id="Selected" name="Selected" type="checkbox" value="true" />
<input name="Selected" type="hidden" value="false" />
Trab
<input id="Id" name="Id" type="hidden" value="11" />
</p>
The view is created like in this post:
Categories and Subcategories MVC2
now I want to do a post, but how to get the datas?
When I do a post like this:
[HttpPost]
public void myAction(NewHorseModel newHorseModel)
{
// ...
}
Faehigkeit in NewHorseModel is null
Here my ASPX Code:
<div id="Div2">
<%
foreach (Category item2 in Model.Faehigkeit)
{
Html.RenderPartial("Faehigkeit", item2);
}
%>
</div>
The partial view Category (strong typed model Category):
<%
if (Model.Choices != null)
{
foreach (var item in Model.Choices)
{
Html.RenderPartial("Choice", item);
}
}
if (Model.Subcategories != null)
{
foreach (var item in Model.Subcategories)
{
Html.RenderPartial("Faehigkeit", item);
}
}
%>
And the partialview Choices (strongtyped model choice)
<p>
<%: Html.CheckBoxFor(m => m.Selected, new { faehigkeit_ID = Model.Id }) %>
<%: Model.Name %>
<%: Html.HiddenFor(u=>u.Id) %>
</p>
Update
Next test:
in the Faehigkeit.ascx partial I have added this code:
<input type="hidden" name="Faehigkeit[<%=Model.Id%>].Id" value="<%=Model.Id%>" />
<input type="hidden" name="Faehigkeit[<%=Model.Id%>].Name" value="<%: Model.Name%>" />
in the Choices.ascx partial I have added following code:
<input type="checkbox" name="Faehigkeit[0].Choices[<%=Model.Id%>].Selected" />
I don't need to know which choice is in wich category. I kust need to know which choice ID is checked and which on not.
The HTML-Output looks like this:
<input type="hidden" name="Faehigkeit[1].Id" value="1" />
<input type="hidden" name="Faehigkeit[1].Name" value="Qualität der Gangarten" />
<input type="hidden" name="Faehigkeit[1].Choices[4].Id" value="4" />
<input type="checkbox" name="Faehigkeit[1].Choices[4].Selected" />
My controler looks like this:
[HttpPost]
public ActionResult CreateNewHorse(NewHorseModel collection)
{
if (User.Identity.IsAuthenticated)
{
return View();
}
else
{
return View("Account/LogOn");
}
}
If I try to get the value of "Faehigkeit" -> "Choices" Every thing is Null (the Name of the "Faehigkeit", the ID of "Faehigkeit", and there are no choices
An image that shows the content of the NewHorseModel during debuging:
http://i.stack.imgur.com/6yLZW.png
Thank you very much!
There are 2 blog posts that I've written and will address your problem:
How to post IList<T> to controller actions is explained here and will guide you from start to finish so you'll understand how it actually works and why.
And since you may have have complex JSON objects on the client side and would like them to be model bound on the server in your action method (as is in your case), this post may be as well an interesting read. It explains the problem of sending complex JSON objects and provides a simple jQuery plugin that converts client objects into a form that will easily be data bound to your strong type action method parameters.
Note: There's also the possibility of using JsonValueProviderFactory as explained by Phil Haack, but that solution requires changes on the client as well as on the server side (because you're using MVC2).
Based on your code
You've only provided some parts of your code (and some that aren't really relevant but anyway) and I'm going to make an observation for your case.
All input fields that you wish to model bind on the server need to have correct names. From the rendered checkbox names we can see that is not the case at all.
Based on your model, your inputs should be named as (never mind input types because only you know which ones should be rendered and as which type):
<!-- erste fähigkeit -->
<input name="Faehigkeit[0].Id" />
<input name="Faehigkeit[0].Name" />
<input name="Faehigkeit[0].Beschreibung" />
<input name="Faehigkeit[0].Subcategories[0].Id" />
<input name="Faehigkeit[0].Subcategories[0].Name" />
...
<input name="Faehigkeit[0].Choices[0].Id" />
<input name="Faehigkeit[0].Choices[0].Name" />
<input name="Faehigkeit[0].Choices[0].Beschreibung" />
<input name="Faehigkeit[0].Choices[0].Selected" />
...
<input name="Faehigkeit[0].Choices[x].Id" /> <!-- "x" could be any number -->
...
<input name="Faehigkeit[0].Parent" />
<!-- zwite fähigkeit -->
<input name="Faehigkeit[1].Id" />
...
<!-- usw. -->
Based on this complex hierarchical model this form can be huge. And you probably don't wish to send all properties because you only need some that are relevant. But the main thing is that input naming should be as described.
Extremely important: I should point out that indexes (ie. Faehigkeit[0]) are not supposed to relate to IDs, but are rather array/list item indexes. They should be consecutive so they should always start at 0 and should be incremented by 1 to the last N hence should have no gaps whatsoever. Believe me I've tested that when I was writing my blog post. Otherwise model binding on the server will fail. Make sure you pass this requirement! Based on your edited question this is not the case, because you're putting in IDs instead of indexes.
If you'd transfer your data as JSON to the client, you'd have an object on the client as:
var data = {
Faehigkeit: [
{
Id: 1,
Name: "Some name",
Beschreibung: "Some description",
Subcategories: [
{ ... },
{ ... },
...
],
Choices: [
{ ... },
{ ... },
...
]
},
{ ... },
...
]
};
And if your client side view manipulated this object directly you could then afterwards send it back to the server by means of jQuery Ajax call ie:
$.ajax({
type: "POST",
url: "someController/myAction",
data: $.toDictionary(data), // this is my jQuery plugin mentioned earlier
success: function() { ... },
error: function() { ... }
});
So the choice is yours, but in either case, field names should be correct otherwise your model won't be bound to your parameter and you won't be able to use it.
You could try with <%= Html.EditorFor(m => m); %> but that may not be the kind of form you'd like to use. In such case manual input naming would have to be used. Or you can as well write some custom code.
One of the ways would be to chaneg your partial views mode types to become for instance Tuple<string, Category>. String would tell it what string should be pre-pent to your field names.
Html.RenderPartial("Faehigkeit", Tuple.New("Faehigkeit[0]", item2));
And then when you go along, previous data should be always added so your subcategories' lists and their respected subobjects will have correct input form names.
Not nice, but I suppose it's the only way to make it.
Usually if you put the HttpPost as an attribute of your action, its something like:
[HttpPost]
public void myAction(NewHorseModel newHorseModel)
{;}
Then put the class type as your argument it should autobind it for you, if there is anything crazy that you need to do, or are posting from an external non ASP page to this action you can just use the FormCollection (i think) as your argument and thats a glorified Dictionary containing all your elements and values.

Categories

Resources