Pass Object from view to controller using mvc4 - asp.net-mvc

View
#if (weekMaster != null)
{
using (Html.BeginForm("UpdatePlan", "generalPlan", FormMethod.Post, new { }))
{
<table class="table-bordered">
<tr>
#foreach (TermMaster obj in weekMaster.ToList())
{
<td align="center">
<span> #obj.termStartDate.ToString("dd MMM") - #obj.termEndDate.ToString("dd MMM")</span>
<br />
<input type="hidden" name="ObjHid" value="#obj" />
<input type="hidden" name="startDate" value="#obj.termStartDate" />
<input type="hidden" name="endDate" value="#obj.termEndDate" />
<input type="text" style="width:80%" name="weekSession" />
</td>
}
<td>
<input type="submit" value="Update" class="btn-primary" />
</td>
</tr>
</table>
} }
Controller
[HttpPost]
public ActionResult UpdatePlan(List<DateTime> startDate, List<DateTime> endDate, List<int> weekSession, List<TermMaster> ObjHid)
{
return View();
}
I am trying pass Class Object from View to Controller above TermMaster class Object pass using input method <input type="hidden" name="ObjHid" value="#obj" /> but showing NULL value if pass single value like startDate and endDate then it work fine.
What is wrong in my code? how to pass class object List in Post Method?
Please refer Image

You can not bind objects to controller from your input. You can serialize object to json. In the controller you can take your inputs value as string and deserialize it.

You have to do it by below approach.
Create a model instead of multiple parameters, and use index in cshtml.
public class model
{
public List<DateTime> startDate { get; set; }
public List<DateTime> endDate { get; set; }
public List<int> weekSession { get; set; }
public List<TermMaster> ObjHid { get; set; }
}
CSHTML
#{ int i = 0; }
#foreach (TermMaster obj in weekMaster.ToList())
{
<td align="center">
<span> #obj.termStartDate.ToString("dd MMM") - #obj.termEndDate.ToString("dd MMM")</span>
<br />
<input type="hidden" name="ObjHid[#i].termStartDate" value="#obj.termStartDate.ToString("dd MMM")" />
<input type="hidden" name="ObjHid[#i].termStartDate" value="#obj.termStartDate.ToString("dd MMM")" />
<input type="hidden" name="startDate[#i]" value="#obj.termStartDate" />
<input type="hidden" name="endDate[#i]" value="#obj.termEndDate" />
<input type="text" style="width:80%" name="weekSession[#i]" />
</td>
i++
}

Related

ASP.NET MVC : bind form with List<Model> in view model

I have a view model with the following properties:
// I set the values from the database
public List<Document> AvailableDocuments { get; set; }
// I need to set the values from a front end <form>
public List<RequiredDocument> RequiredDocuments { get; set; }
The RequiredDocument model contains the following properties:
// This should be an Id, maybe a hidden input
public Document Document { get; set; }
// This should be a number input
public int RequiredCopies { get; set; }
// This should be a checkbox
public bool IsRequired { get; set; }
In my view I'm looping through AvailableDocuments and every iteration should bind to a RequiredDocument model (where the user may set the values for the RequiredCopies number).
The form is submitted via Ajax. How can I bind the form to RequiredDocuments?
#foreach (Document doc in Model.AvailableDocuments)
{
<div class="reqdoc">
<!-- RequiredDocument.Document -->
<input type="hidden" name="Document" value="#doc.Id" />
<div class="form-check">
<!-- RequiredDocument.IsRequired -->
<input class="form-check-input" type="checkbox" value="" />
<label class="form-check-label">
#doc.Name
</label>
</div>
<!-- RequiredDocument.RequiredCopies -->
<input class="form-control" type="number" />
</div>
}
You can use this kind of for loop I am doing similar in my projects & it works
<table>
#for (int i = 0; i < (int)ViewBag.Count; i++)
{
#Html.HiddenFor(model => model.AvailableDocuments.ToList()[i].ID)
<tr>
<td>
#Html.CheckBoxFor(model => model.RequiredDocuments.ToList()[i].IsRequired, new { id = "chk_" + i, #class = "custom-checkbox" })
</td>
<td>
#Html.DisplayFor(model => model.AvailableDocuments.ToList()[i].Name)
</td>
<td>
#Html.TextBoxFor(model => model.RequiredDocument.ToList()[i].RequiredCopies, new { id = "RequiredCopies" + i, #class = "form-control" })
</td>
</tr>
}
</table>
Just pass a ViewBag.Count from Your get method.
Work with index and modify the name attribute as:
#{
int i = 0;
foreach (Document doc in Model.AvailableDocuments)
{
<div class="reqdoc">
<!-- RequiredDocument.Document -->
<input type="hidden" name="RequiredDocuments[#i].Document.Id" value="#doc.Id" />
<div class="form-check">
<!-- RequiredDocument.IsRequired -->
<input class="form-check-input" type="checkbox" value="" name="RequiredDocuments[#i].IsRequired" />
<label class="form-check-label">
#doc.Name
</label>
</div>
<!-- RequiredDocument.RequiredCopies -->
<input class="form-control" type="number" name="RequiredDocuments[#i].RequiredCopies" />
</div>
i++;
}
}

mvc passing data from view to controller

My Controller
public class OgrenciController : Controller
{
[HttpPost]
public ActionResult home(int perId)
{
if(perId=="anything")
{
//something
}
return View();
}
}
This is my view
#foreach (var item in Model)
{
siraNo++;
<form method="post">
<input type="radio" name="perId" value="#item.specialId">
<input type="submit" value="send" />
</form>
}
but in the POST method, perId not take anythings
use something like this.
#using (Html.BeginForm())
{
foreach (var item in Model)
{
<input type="radio" name="perId" value="#item.specialId"><br /><br />
}
<input type="submit" ur value="send" />
}

Binding Complex Types in MVC5

I'm a newbie developer trying to develope a web application with asp .net mvc 5 for personel usage. The website kind of a quiz maker that I can insert Russian words with meanings and prepare a quiz by using these words.
When I trying to code the quiz page and post the data the the action method I faced some problem that I couldn't get around. I iterated through the Model, read the data and wrote them to the page. Now, what I want to do is, when I post the form, I want to get each question string and selected answer (maybe in this format: imgur.com/QETnafx). Therefore, I can easily check the answer string whether it is true or not.
I checked the following tutorials out:
Model Binding To A List by Phil Haack and ASP.NET Wire Format for Model Binding to Arrays, Lists, Collections, Dictionaries by Scott Hanselman
I hope I explained the situation clearly. If you need more information I can happily provide.
ViewModel
public class QuizInitializationModel
{
public List<Question> Questions { get; set; }
}
public class QuestionString
{
public int Id { get; set; }
public string WordString { get; set; }
}
public class Question
{
public QuestionString QuestionString { get; set; }
public List<AnswerItem> Answers { get; set; }
}
public class AnswerItem
{
public int Id { get; set; }
public string WordString { get; set; }
}
VIEW
#using (Html.BeginForm("Begin", "Quiz", FormMethod.Post))
{
<table class="table table-striped table-condensed table-bordered">
#for (int i = 0; i < Model.Questions.Count; i++)
{
<tr>
<td>
#Html.Label(Model.Questions[i].QuestionString.WordString)
</td>
<td>
#for (int item = 0; item < Model.Questions[0].Answers.Count; item++)
{
#Html.Label(Model.Questions[i].Answers[item].WordString)#:
#Html.RadioButton("array" + "[" + #i + "]" + "." + Model.Questions[i].QuestionString.WordString, Model.Questions[i].Answers[item].Id)<br />
}
</td>
</tr>
}
</table>
<input type="submit" value="Send" class="btn btn-primary" />
}
OUTPUT
<form action="/Admin/Quiz/Begin" method="post">
<table class="table table-striped table-condensed table-bordered">
<tr>
<td>
<label for="">вулкан</label>
</td>
<td>
<label for="trade">trade</label>
<input id="array_0________" name="array[0].вулкан" type="radio" value="18" /><br />
<label for="volcano">volcano</label>
<input id="array_0________" name="array[0].вулкан" type="radio" value="24" /><br />
<label for="talk__conversation">talk, conversation</label>
<input id="array_0________" name="array[0].вулкан" type="radio" value="15" /><br />
<label for="time">time</label>
<input id="array_0________" name="array[0].вулкан" type="radio" value="13" /><br />
<label for="income">income</label>
<input id="array_0________" name="array[0].вулкан" type="radio" value="21" /><br />
</td>
</tr>
<tr>
<td>
<label for="">мама</label>
</td>
<td>
<label for="universe">universe</label>
<input id="array_1______" name="array[1].мама" type="radio" value="25" /><br />
<label for="peace">peace</label>
<input id="array_1______" name="array[1].мама" type="radio" value="2" /><br />
<label for="value">value</label>
<input id="array_1______" name="array[1].мама" type="radio" value="20" /><br />
<label for="mom__mama">mom, mama</label>
<input id="array_1______" name="array[1].мама" type="radio" value="17" /><br />
<label for="industry">industry</label>
<input id="array_1______" name="array[1].мама" type="radio" value="19" /><br />
</td>
</tr>
</table>
And how can i fix the ids of the labels like "array_1______" ?
They appeared when I added this code "array" + "[" + #i + "]" + "." to the RadioButton control for the purpose of assign an index for each answer.
Html helpers replace invalid characters with an underscore (a period is actually not invalid, but would cause problems with jquery so its also replaced an underscore). However id attribute is not the problem, although you are generating duplicates which is invalid html.
Your manually generating the name attribute for the radio buttons which have no relationship to any property in your model so wont be bound when you post back. Your model needs to include a property you can bind the selected answer to. Modify the Question model to
public class Question
{
public QuestionString QuestionString { get; set; }
public List<AnswerItem> Answers { get; set; }
public int SelectedAnswer { get; set; } // add this
}
and modify the view to
#using (Html.BeginForm()) // note parameter not necessary if your posting to the same controller/action
{
#for (int i = 0; i < Model.Questions.Count; i++)
{
...
#Html.HiddenFor(m => m.Questions[i].QuestionString.Id)
<h2>#Model.Questions[i].QuestionString.WordString)</h2>
...
#foreach(var answer in Model.Questions[i].Answers)
{
var id = string.Format("{0}-{1}", #i, answer.Id);
#Html.Label(id, answer.WordString)
#Html.RadioButtonFor(m => m.Questions[i].SelectedAnswer, answer.ID, new { id = id })
}
....
}
<input type="submit" value="Send" class="btn btn-primary" />
}
The radio buttons are now bound to the SelectedAnswer property and when you post back, the value will be the ID of the selected AnswerItem
Note also:
A hidden input has been added for the ID of the question so the
question can be identified on post back
The question text is in a heading tag (could be another tag), but a
label is not appropriate - a label is an element associated with a
control (for setting focus to the control) but you don't have an
associated control
A unique id is created in the foreach loop so you can give each
radio button a unique id (so the html is valid) and associate the
label (the answer text) with the button

Accepting params or raw data in controller?

I was wondering if it would be possible having a "params" argument in a controller function, or something similar which would allow me to process X amount of entries in my form.
For instance, I have a form which has X amount of "name" elements, which are auto-generated through jQuery. An example of these name elements could be the following:
<input type="text" name="studentName1"></input>
<input type="text" name="studentName2"></input>
<input type="text" name="studentName3"></input>
Now, there's a different amount of student names every time, so this makes it quite complex for me to handle the form data in my controller. I had something like the following 2 examples in mind, but of course they wouldn't work in reality.
[HttpPost]
public ActionResult PostStudentNames(params string[] studentNames)
Or:
[HttpPost]
public ActionResult PostStudentNames(string[] formValues)
Can I achieve something similar to that?
I just want to chime in with a different approach you can use for this. If it's more convenient, you can model bind directly to collections of primitive or complex types. Here's 2 examples:
index.cshtml:
#using (Html.BeginForm("ListStrings", "Home"))
{
<p>Bind a collection of strings:</p>
<input type="text" name="[0]" value="The quick" /><br />
<input type="text" name="[1]" value="brown fox" /><br />
<input type="text" name="[2]" value="jumped over" /><br />
<input type="text" name="[3]" value="the donkey" /><br />
<input type="submit" value="List" />
}
#using (Html.BeginForm("ListComplexModel", "Home"))
{
<p>Bind a collection of complex models:</p>
<input type="text" name="[0].Id" value="1" /><br />
<input type="text" name="[0].Name" value="Bob" /><br />
<input type="text" name="[1].Id" value="2" /><br />
<input type="text" name="[1].Name" value="Jane" /><br />
<input type="submit" value="List" />
}
Student.cs:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
HomeController.cs:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ListStrings(List<string> items)
{
return View(items);
}
public ActionResult ListComplexModel(List<Student> items)
{
return View(items);
}
}
ListStrings.cshtml:
#foreach (var item in Model)
{
<p>#item</p>
}
ListComplexModel.cshtml:
#foreach (var item in Model)
{
<p>#item.Id. #item.Name</p>
}
The first form simply binds a list of strings. The second, binds the form data to a List<Student>. By using this approach, you can let the default model binder do some of the tedious work for you.
Updated for comment
Yes you can do that too:
Form:
#using (Html.BeginForm("ListComplexModel", "Home"))
{
<p>Bind a collection of complex models:</p>
<input type="text" name="[0].Id" value="1" /><br />
<input type="text" name="[0].Name" value="Bob" /><br />
<input type="text" name="[1].Id" value="2" /><br />
<input type="text" name="[1].Name" value="Jane" /><br />
<input type="text" name="ClassId" value="13" /><br />
<input type="submit" value="List" />
}
Controller action:
public ActionResult ListComplexModel(List<Student> items, int ClassId)
{
// do stuff
}
Mathias,
This works perfectly well without recourse to the params object. your form controls:
<input type="text" name="studentName" />
<input type="text" name="studentName" />
<input type="text" name="studentName" />
<input type="text" name="professorName" />
You would use the FormCollection object, which will contain all your form elements as either comma separated lists (if a control array) or as single properties. In the above example, this is what we'd get:
[HttpPost]
public ActionResult PostStudentNames(FormCollection formValues)
{
// basic check for rogue commas inside input controls
// would need far more sophistication in a #real# app :)
var valueStudents = formValues["studentName"].Split(',')
.Where(x => x.Length > 0).ToArray();
var valueProfessor = formValues["professorName"];
// other stuff
}
etc... At least, this is my recollection of this from a recent project. :)
<input type="text" name="studentName[0]"></input>
<input type="text" name="studentName[1]"></input>
<input type="text" name="studentName[2]"></input>
public ActionResult PostStudentNames(string[] studentName)
{
}

model binding of non-sequential arrays

I am having a table in which i`m dynamically creating and deleting rows. How can I change the code such that the rows be added and deleted and the model info property filled accordingly.
Bearing in mind that the rows can be dynamically created and deleted, I may have Info[0], Inf0[3], info[4]... My objective is to be able to bind the array even if it`s not in sequence.
Model
public class Person
{
public int[] Size { get; set; }
public string[] Name { get; set; }
public Info[]info { get; set; }
}
public class Info
{
public string Address { get; set; }
public string Tel { get; set; }
View
<script type="text/javascript" language="javascript">
$(function () {
var count = 1;
$('#AddSize').live('click', function () {
$("#divSize").append('</br><input type="text" id="Size" name="Size" value=""/><input type = "button" id="AddSize" value="Add"/>');
});
$('#AddName').live('click', function () {
$("#divName").append('</br><input type="text" id="Name" name="Name" value=""/><input type = "button" id="AddName" value="Add"/>');
});
$('#AddRow').live('click', function () {
$('#details').append('<tr><td>Address</td><td> <input type="text" name="Info[' + count + '].Address"/></td><td>Tel</td><td><input type="text" name="Info[' + count++ + '].Tel"/></td> <td><input type="button" id="AddRow" value="Add"/> </td></tr>');
});
});
</script>
</head>
<body>
<form id="closeForm" action="<%=Url.Action("Create",new{Action="Create"}) %>" method="post" enctype="multipart/form-data">
<div id="divSize">
<input type="text" name="Size" value=""/> <input type="button" value="Add" id="AddSize" />
</div>
<div id="divName">
<input type="text" name="Name" value=""/> <input type="button" value="Add" id="AddName" />
</div>
<div id="Tab">
<table id="details">
<tr><td>Address</td><td> <input type="text" name="Info[0].Address"/></td><td>Tel</td><td><input type="text" name="Info[0].Tel"/></td> <td><input type="button" id="AddRow" value="Add"/> </td></tr>
</table>
</div>
<input type="submit" value="Submit" />
</form>
</body>
}
Controller
public ActionResult Create(Person person)
{
return new EmptyResult();
}
Here's a nice blog post that you might find helpful.

Resources