Scenario :
The user can enter his/her name, grade and tutor's name. and then needs to enter subject marks. The subject form field is dynamic, in other words, one user may have 5 subjects and the other one may have 3 only.
Current Fix:
Currently, i have fixed this with spaghetti code, making use of jQuery's append
on button click event. and passing the form data as FormCollection and then changed the formcollection to model.
What i need:
I need to make use of Model instead of form collection. That is, i need to pass the form data as model not formcollection.
Here's what I did:
Model:
public class StudentModel
{
public string Name { get; set; }
public string Grade { get; set; }
public string Tutor { get; set; }
public List<SubjectModel> Subjects { get; set; }
}
public class SubjectModel
{
public string Subject { get; set; }
}
Controller:
public class HomeController : Controller
{
....
[HttpPost]
public ActionResult Index(FormCollection form)
{
var subjects = form["Subject"].Split(',');
var modelsubjects = new List<SubjectModel>();
foreach (var subject in subjects)
{
modelsubjects.Add(new SubjectModel() { Subject = subject });
}
var model = new StudentModel();
model.Name = form["Name"];
model.Grade = form["Grade"];
model.Tutor = form["Tutor"];
model.Subjects = modelsubjects;
//Here I get the model from a dynamic form
return View();
}
}
View:
<div class="jumbotron">
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<div class="row">
<div class="col-sm-3">
<label for="Name">Name</label>
<input type="text" id="Name" name="Name" />
</div>
<div class="col-sm-3">
<label for="Grade">Grade</label>
<input type="text" id="Grade" name="Grade" />
</div>
<div class="col-sm-3">
<label for="Tutor">Tutor</label>
<input type="text" id="Tutor" name="Tutor" />
</div>
<div class="col-sm-1">
<a class="btn btn-primary" id="addSubject">Add Subject</a>
</div>
<div class="col-sm-1">
<input class="btn btn-primary" type="submit" value="Submit" />
</div>
</div>
<div id="subjectInfo" style="padding-top:10px;">
</div>
}
</div>
<script type="text/javascript">
var count = 0;
$("#addSubject").click(function () {
$("#subjectInfo").append("<div class='row'>" +
"<div class='col-sm-8'>" +
"<label for='Subject_" + count + "'>Subject " + count + "</label>" +
"<input type='text' name='Subject' id='Subject_" + count + "' />" +
"</div>" +
"</div>");
count++;
});
</script>
Any advice would be helpful. Thank you.