Hello, I've been searching the web for a solution but I can't really find it or manage to convert the code to my own code. At the moment we are working at a project for school and we would like to pass through data from a dropdownlist in our view of Index()
to a controller with the ActionResult genBlocks()
The code of our genBlocks()
public ActionResult genBlocks()
{
int blocksPerDay = 4;
int strH, strM;
strH = Convert.ToInt32(Request["StartTimes"]);
strM = Convert.ToInt32("0");
List<Block> blocks = new List<Block>();
for (int i = 0; i < blocksPerDay; i++)
{
if (i != 0)
{
strH = blocks[i - 1].EndTime.Hour;
strM = blocks[i - 1].EndTime.Minute;
}
else
{
strH = strH;
strM = strM;
}
Block block = new Block
{
FieldDayId = 1,
Available = true,
StartTime = DateTime.Today + new TimeSpan(strH, strM, 0),
EndTime = DateTime.Today + new TimeSpan(strH, strM + (db.Sports.Find(1).Duration * (i + 1)), 0),
};
blocks.Add(block);
db.Blocks.Add(block);
db.SaveChanges();
}
return RedirectToAction("Index");
}
Hmm, I can't really figure it out with your solution.
We tought about something like this in the controller
public ActionResult genBlocks(int Start, int End) { }
and in the view
@Html.ActionLink("Generate Blocks", "genBlocks", new {start = hour, end = hour})
This works but only with hard coded numbers, like start = 8. If we could get the value of our dropdownlist (as in the example above) in that line it would work out..
Anyway thanks!
You are correct on @Html.ActionLink("Generate Blocks", "genBlocks", new {start = hour, end = hour}), send "start" and "end" to controller, and controller recive
these value at "genBlocks(int Start, int End) { }". This is also work at my project. My reply is another way how to send to a controller. It has been tested.
I can not find (due to my minim knowledge) "hour" come from in at the view. Html.ActionLink it self have several parameter that we can pass to a controller. In my sample I pass my object.
In the following code, I can not find the item or object you send to controller from DropDownList.
public ActionResult Create()
{
PopulateDepartmentsDropDownList();
return View();
}
[HttpPost]
public ActionResult Create(Course course)
{
try
{
if (ModelState.IsValid)
{
unitOfWork.CourseRepository.Insert(course);
unitOfWork.Save();
return RedirectToAction("Index");
}
}
catch (DataException)
{
//Log the error (add a variable name after DataException)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
PopulateDepartmentsDropDownList(course.DepartmentID);
return View(course);
}
private void PopulateDepartmentsDropDownList(object selectedDepartment = null)
{
var departmentsQuery = unitOfWork.DepartmentRepository.Get(
orderBy: q => q.OrderBy(d => d.Name));
ViewBag.DepartmentID = new SelectList(departmentsQuery, "DepartmentID", "Name", selectedDepartment);
}
elsticky
Member
10 Points
6 Posts
How to pass data from view to controller
May 20, 2012 12:41 PM|LINK
Hello, I've been searching the web for a solution but I can't really find it or manage to convert the code to my own code. At the moment we are working at a project for school and we would like to pass through data from a dropdownlist in our view of Index() to a controller with the ActionResult genBlocks()
The code of our genBlocks()
public ActionResult genBlocks() { int blocksPerDay = 4; int strH, strM; strH = Convert.ToInt32(Request["StartTimes"]); strM = Convert.ToInt32("0"); List<Block> blocks = new List<Block>(); for (int i = 0; i < blocksPerDay; i++) { if (i != 0) { strH = blocks[i - 1].EndTime.Hour; strM = blocks[i - 1].EndTime.Minute; } else { strH = strH; strM = strM; } Block block = new Block { FieldDayId = 1, Available = true, StartTime = DateTime.Today + new TimeSpan(strH, strM, 0), EndTime = DateTime.Today + new TimeSpan(strH, strM + (db.Sports.Find(1).Duration * (i + 1)), 0), }; blocks.Add(block); db.Blocks.Add(block); db.SaveChanges(); } return RedirectToAction("Index"); }Our Index() View
@model IEnumerable<PowerWaveMDF.Models.Block> @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table> <tr> <th> FieldDay </th> <th> Available </th> <th> StartTime </th> <th> EndTime </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.FieldDay.Date) </td> <td> @Html.DisplayFor(modelItem => item.Available) </td> <td> @Html.DisplayFor(modelItem => item.StartTime) </td> <td> @Html.DisplayFor(modelItem => item.EndTime) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.BlockId }) | @Html.ActionLink("Details", "Details", new { id=item.BlockId }) | @Html.ActionLink("Delete", "Delete", new { id=item.BlockId }) </td> </tr> } </table> @Html.DropDownList("StartTimes", String.Empty) <div class="button">@Html.ActionLink("Delete All", "deleteAllBlocks")</div> <div id="genBlocks" class="button">@Html.ActionLink("Generate Blocks", "genBlocks")</div>As you can see I tried a Request but that doesn't work out
jsiahaan
Contributor
2324 Points
597 Posts
Re: How to pass data from view to controller
May 20, 2012 01:55 PM|LINK
Hi,
I can not find the object on your view at DropDown Element (I am new to ASP.MVC but I just finished similar case).
Here my Sender View send an object named "item":
@foreach (var item in Model) { <tr> <td>@Html.DisplayFor(modelItem => item.FullName)</td> <td>@Html.DisplayFor(modelItem => item.CategoryName)</td> <td>@Html.DisplayFor(modelItem => item.BirthDate)</td> <td>@Html.DisplayFor(modelItem => item.NationalIDNumber)</td> <td>@Html.DisplayFor(modelItem => item.AddressLine1)</td> <td>@Html.DisplayFor(modelItem => item.City)</td> <td style="padding-left: 15px"> @Html.ActionLink("Student", "Create", "Student", item, null) | @Html.ActionLink("Instructor", "Create", "Instructor", item, null) </td> </tr> }Here my controller receive the "item" named "PersonInfo personInfo", and send ViewData.Model and ViewBag.FullName
public ActionResult Create(PersonInfo personInfo) { if (personInfo != null) { ViewBag.FullName = personInfo.FullName; CoursePerson student = new CoursePerson(); student.PersonID = personInfo.BusinessEntityID; student.EnrollmentDate = DateTime.Now; student.Discriminator = "Student"; ViewData.Model = student; } return View(); }Here my receiver view as "model" from "ViewDataModel" and @ViewBag.FullName
@model CourseCenter.Models.CoursePerson @{ ViewBag.Title = "Create"; } <h2>Create</h2> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>Student</legend> @Html.HiddenFor(model => model.PersonID) @Html.HiddenFor(model => model.Discriminator) <div class="editor-label"> @Html.LabelFor(model => model.PersonInfo.FullName) @ViewBag.FullName </div> <div class="editor-label"> @Html.LabelFor(model => model.EnrollmentDate) </div> <div class="editor-field"> @Html.EditorFor(model => model.EnrollmentDate) @Html.ValidationMessageFor(model => model.EnrollmentDate) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div>Hope this can help.
Indonesian Humanitarian Foundation
elsticky
Member
10 Points
6 Posts
Re: How to pass data from view to controller
May 20, 2012 02:13 PM|LINK
Hmm, I can't really figure it out with your solution.
We tought about something like this in the controller
public ActionResult genBlocks(int Start, int End) { }
and in the view
This works but only with hard coded numbers, like start = 8. If we could get the value of our dropdownlist (as in the example above) in that line it would work out..
Anyway thanks!
jsiahaan
Contributor
2324 Points
597 Posts
Re: How to pass data from view to controller
May 20, 2012 02:44 PM|LINK
Hi,
You are correct on @Html.ActionLink("Generate Blocks", "genBlocks", new {start = hour, end = hour}), send "start" and "end" to controller, and controller recive these value at "genBlocks(int Start, int End) { }". This is also work at my project. My reply is another way how to send to a controller. It has been tested.
I can not find (due to my minim knowledge) "hour" come from in at the view. Html.ActionLink it self have several parameter that we can pass to a controller. In my sample I pass my object.
In the following code, I can not find the item or object you send to controller from DropDownList.
@Html.DropDownList("StartTimes", String.Empty) <div class="button">@Html.ActionLink("Delete All", "deleteAllBlocks")</div> <div id="genBlocks" class="button">@Html.ActionLink("Generate Blocks", "genBlocks")</div>Have fun.
Indonesian Humanitarian Foundation
elsticky
Member
10 Points
6 Posts
Re: How to pass data from view to controller
May 20, 2012 02:50 PM|LINK
here hour is just a random number to fill in. So when you do something like this
It will work. But i would like the selected value of my dropdownlist
@Html.DropDownList("StartTimes", String.Empty)But i don't know how to retrieve the selected value of that dropdownlist. The select list is defined in the controller itself.
jsiahaan
Contributor
2324 Points
597 Posts
Re: How to pass data from view to controller
May 20, 2012 03:18 PM|LINK
Hi,
I have this code, but I can not test, can you do the test?
@Html.DropDownList("StartTimes", String.Empty) <input type="submit" value="Filter" /> <div id="genBlocks" class="button">@Html.ActionLink("Generate Blocks", "genBlocks", new { start = "Filter", end = "Filter" })</div>Indonesian Humanitarian Foundation
jsiahaan
Contributor
2324 Points
597 Posts
Re: How to pass data from view to controller
May 20, 2012 03:26 PM|LINK
Hi,
May be you can find on this code:
View Code:
@using (Html.BeginForm()) { <p>Select Department: @Html.DropDownList("SelectedDepartment","All") <input type="submit" value="Filter" /></p> </p> }Controller:
public ActionResult Create() { PopulateDepartmentsDropDownList(); return View(); } [HttpPost] public ActionResult Create(Course course) { try { if (ModelState.IsValid) { unitOfWork.CourseRepository.Insert(course); unitOfWork.Save(); return RedirectToAction("Index"); } } catch (DataException) { //Log the error (add a variable name after DataException) ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator."); } PopulateDepartmentsDropDownList(course.DepartmentID); return View(course); } private void PopulateDepartmentsDropDownList(object selectedDepartment = null) { var departmentsQuery = unitOfWork.DepartmentRepository.Get( orderBy: q => q.OrderBy(d => d.Name)); ViewBag.DepartmentID = new SelectList(departmentsQuery, "DepartmentID", "Name", selectedDepartment); }Please let me know the result.
Indonesian Humanitarian Foundation
elsticky
Member
10 Points
6 Posts
Re: How to pass data from view to controller
May 20, 2012 04:43 PM|LINK
Isn't that just code to fill the dropdownlist? I don't really get how to change my code in something like that..
jsiahaan
Contributor
2324 Points
597 Posts
Re: How to pass data from view to controller
May 20, 2012 04:59 PM|LINK
Yes,
The code has been tested. I did it based on ContosoUniversity tutorial on this address: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc
Indonesian Humanitarian Foundation