Html.BeginForm call the right Action in Controller - asp.net-mvc

There are a lot of topics related to this question but I still did't figured out what I'm doing wrong.
I have a database where I manage access of different users to folders. On my View the User can select Employees which should have access to certain folder. Then I want to pass the selected Employees to Controller, where the database will be updated.
My Problem is: The right Action in the Controller class didn't get invoked.(I have a breakpoint inside)
Here is the View
#model DataAccessManager.Models.EmployeeSelectionViewModel
#{
ViewBag.Title = "GiveAccessTo";
}
#using (Html.BeginForm("SubmitSelected", "FolderAccessController", FormMethod.Post, new { encType = "multipart/form-data"}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.fr_folder_uid_fk)
<div class="form-horizontal">
<input type="submit" value="Save" id="submit" class="btn btn-default" />
<table id="tableP">
<thead>
<tr>
<th>Selection</th>
<th>Second Name</th>
<th>First Name</th>
<th>Department</th>
</tr>
</thead>
<tbody id="people">
#Html.EditorFor(model => model.People)
</tbody>
</table>
</div>
</div>
</div>
}
Here is the Controller reduced to the minimum
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SubmitSelected(EmployeeSelectionViewModel model)
{
return View();
}
More Details: I am not sure what is causing the problem, so here some more details.
The view is strongly typed to EmployeeSelectionViewModel, it represets the table with all Employees as a List here is the the code:
public class EmployeeSelectionViewModel
{
public List<SelectEmployeeEditorViewModel> People { get; set; }
public EmployeeSelectionViewModel()
{
this.People = new List<SelectEmployeeEditorViewModel>();
}
public Int64 fr_folder_uid_fk { get; set; }
public IEnumerable<string> getSelectedIds()
{
// Return an Enumerable containing the Id's of the selected people:
return (from p in this.People where p.Selected select p.fr_mavnr_fk).ToList();
}
}
The SelectEmployeeEditorViewModel represents one row of the table with all Employees.
public class SelectEmployeeEditorViewModel
{
public bool Selected { get; set; }
public string fr_mavnr_fk { get; set; }
public string firstName { get; set; }
public string secondName { get; set; }
public string dpt { get; set; }
}
And it has a View which create the checkboxes for each Employee
#model DataAccessManager.Models.SelectEmployeeEditorViewModel
<tr>
<td style="text-align:center">
#Html.CheckBoxFor(model => model.Selected)
#Html.HiddenFor(model => model.fr_mavnr_fk)
</td>
<td>
#Html.DisplayFor(model => model.secondName)
</td>
<td>
#Html.DisplayFor(model => model.firstName)
</td>
<td>
#Html.DisplayFor(model => model.dpt)
</td>
</tr>
The /FolderAccessController/SubmitSelected URL is called in the browser when I press the Submit button, but as mentioned the Action isn't invoked.
EDIT: I get the HTTP 404 not found error after pressing the button

Try removing the "Controller" word from your Html.BeginForm() second parameter, it's not needed.
#using (Html.BeginForm("SubmitSelected", "FolderAccess", FormMethod.Post, new { encType = "multipart/form-data"}))

Thiago Ferreira and haim770 Thanks a lot! The solution is to use the combination of your comments. So:
#using (Html.BeginForm("SubmitSelected", "FolderAccess", FormMethod.Post))
at the Controller

Related

Add database model (for listing records) to a View associated already with a model (for textboxes)

I'm quite new to MVC and still making myself familiar to how MVC works. So basically, I have a User model that has a Create view. I'm using Razor syntax to get the variables from User model:
Create.cshtml
#model CDS.Models.UserModels
#{
ViewBag.Title = "Create User";
}
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.firstname)
#Html.TextBoxFor(m => m.firstname)
<input type="submit" id="btnSave" value="Save" class="btn btn-default" />
}
UserModels.cs
namespace CDS.Models
{
public class UserModels
{
public string userid { get; set; }
[Display(Name = "First Name")]
public string firstname{ get; set; }
public IEnumerable<SelectListItem> filteroptions { get; set; }
}
}
I tried auto-generating an Index view from the controller's Index method to list the database records, but found out that the generated Index view is using the Database model (first line of code). I just want to move the code from the Index.cshtml to my Create.cshtml to have the latter View also display the database records. So how will I do that? I've heard that I need to use Javascript for that?
UserController.cs
namespace CDS.Controllers
{
public class UserController : Controller
{
CDSEntities _odb = new CDSEntities(); //My Database
// GET: User
public ActionResult Index()
{
return View(_odb.USR_MSTR.ToList());
}
// GET: User/Create
public ActionResult Create()
{
var filters = GetAllFilters();
var model = new UserModels();
model.filteroptions = GetSelectListItems(filters);
return View(model);
}
}
}
Index.cshtml
#model IEnumerable<CDS.USR_MSTR>
#{
ViewBag.Title = "Index";
}
<p>#Html.ActionLink("Create New", "Create")</p>
<table class="table">
<tr>
<th>#Html.DisplayNameFor(model => model.FIRST_NM)</th>
<th>#Html.DisplayNameFor(model => model.LAST_NM)</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>#Html.DisplayFor(modelItem => item.FIRST_NM)</td>
<td>#Html.DisplayFor(modelItem => item.LAST_NM)</td>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
Please note that I removed the codes that I think unnecessary to post here. These are all just summaries of my classes and HTMLs

Post Multiple Data from View to Controller MVC

I want to post quantity property to Controller (It's an edit action). I'm editing OrderedProductSet which is connected with ProductSet in my SQL Database (I get the name and price from there). How to pass multiple data from the view to controller? How to write method in controller class to receive the data (I'm asking about method arguments in this specific case).
My view:
#model Shop.Models.ProductViewModel#{
ViewBag.Title = "Edycja zamówienia";
}
<h2>Edycja zamówienie</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<table class="table">
<tr>
<th>
<b>Nazwa produktu</b>
</th>
<th>
<b>Cena</b>
</th>
<th>
<b>Ilość</b>
</th>
<th></th>
</tr>
#foreach (var item in Model.orderedProductSet)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ProduktSet.name)
</td>
<td>
#Html.DisplayFor(modelItem => item.ProduktSet.price)
</td>
<td>
#Html.EditorFor(model => item.quantity, new { htmlAttributes = new { #class = "form-control" } })
</td>
</tr>
}
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Potwierdź zmiany" class="btn btn-default" />
</div>
</div>
}
<div>
#Html.ActionLink("Powrót", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
My model (in separated classes of course):
public class ProductViewModel
{
public OrderSet orderSet { get; set; }
public IEnumerable<OrderedProductSet> orderedProduktSet { get; set; }
}
public partial class OrderedProduktSet
{
public int orderNumber{ get; set; }
public int productNumber { get; set; }
public int ilosc { get; set; }
public virtual ProduktSet ProduktSet { get; set; }
public virtual OrderSet OrderSet { get; set; }
}
You need to construct controls for you collection in a for loop or use a custum EditorTemplate for OrderedProduktSet so that the controls are correctly named with indexers and can be bound on post back. Note the for loop approach required that the collection be IList.
#model Shop.Models.ProductViewModel
#using(Html.BeginForm())
{
....
for(int i = 0; i < Model.orderedProductSet.Count; i++)
{
#Html.DisplayFor(m => m.orderedProductSet[i].ProduktSet.name)
....
#Html.EditorFor(m => m.orderedProductSet[i].quantity, new { htmlAttributes = new { #class = "form-control" } })
}
<input type="submit" />
}
Controller (the model will be bound, including the collection of OrderedProductSet)
public ActionResult Edit(ProductViewModel model)
{
....
}
Alternatively, you can create an EditorTemplate
/Views/Shared/EditorTemplates/OrderedProduktSet.cshtml
#model OrderedProduktSet
#Html.DisplayFor(m => m.ProduktSet.name)
#Html.EditorFor(m => m.quantity, new { htmlAttributes = new { #class = "form-control" } })
and in the main view
#model Shop.Models.ProductViewModel
#using(Html.BeginForm())
{
....
#Html.EditorFor(m => m.orderedProductSet)
<input type="submit" />
}
Viewbag is your friend here. You normally pass data from View to Controller in MVC. You can access data set in a Viewbag in the controller in your View.
The simplest way to let your controller handle your view is to create an actionresult method in your controller with the same name as your view.
For example, your view is called Index, thus you would have the following method in your controller to handle the view data:
public ActionResult Index()
{
return View();
}
Accessing a list:
Use a Viewbag.
Controller
Viewbag.MyList = myList
View
#foreach (var item in Viewbag.MyList)
Here is good link for more info:
http://www.asp.net/mvc/overview/older-versions/getting-started-with-aspnet-mvc4/adding-a-view

Passing back child entity from MVC view to controller

I'm trying to delete entries which are marked (checked) in view, but not sure how to pass back the collection back to the controller
my mode is:
Group which has ICollection<SubGroup> SubGroups and SubGroup has ICollection<Event> Events
I pass Group to the view and iterate and display Event details including a checkbox so if it's checked the event entry should be deleted.
When I get the postback to the controller, Group.SubGroups is null
How do I make sure the child entities are passed back to the controller?
Can I use #Html.CheckBox instead Of <input type="checkbox"... ?
Update: Model
public class Group
{
[Key]
public int GroupId { get; set; }
public virtual IList<SubGroup> SubGroups { get; set; }
....
}
public class SubGroup
{
[Key]
public int SubGroupId { get; set; }
public virtual IList<Event> Events { get; set; }
....
}
public class Events
{
[Key]
public int EventId { get; set; }
public string EventName { get; set; }
public bool IsDeleted { get; set; }
....
}
I am passing Group to the view (see below) as the Model and want to delete events which are checked by the user
View:
#using System.Globalization
#model NS.Models.Group
#{
ViewBag.Title = "Edit";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Booking Details</legend>
<div class="display-label">
Group Name
</div>
<div class="display-field">
#Html.DisplayFor(model => model.GroupName)
</div>
<div class="display-field">
#foreach (var b in Model.SubGroup)
{
groupNo += 1;
<table class="main" style="width: 80%; margin-top: 10px">
<tr>
<th>
#Html.DisplayName("Sub Group ")
#Html.DisplayName(b.SubGroupName)
</th>
</tr>
<table class="main" style="width: 80%;">
<tr>
<th>Event</th>
<th>Delete</th>
</tr>
#foreach (var ev in b.Events)
{
<tr>
<td>
#Html.DisplayFor(modelItem => ev.EventName)
</td>
<td>
<input type="checkbox" id="eventToDelete" name="eventToDelete" value="#ev.EventId" />
</td>
</tr>
}
</table>
</table>
}
</div>
<p>
<input type="submit" name="xc" value="Delete" class="button" />
</p>
</fieldset>
}
Thank You
Try this...
public ActionResult ViewName(FormCollection collection)
{
if(collection['eventToDelete']!=null && collection['eventToDelete'].ToString()!="")
{
//delete....
}
return....
}
Try this
public ActionResult ViewName(Group model)
{
if(model != null && ModelState.IsValid)
{
//delete....
}
return....
}

KendoUI listview passing IEnumerable<model> instead of model from editor template in MVC

I've been puzzling over this for a few days now. Basically, I have a view model that contains three IEnumerables of other view models to be displayed in three separate Kendo controls - one as a ListView, and two as GridViews. Each view model has a separate editor template that is used by the corresponding control. The GridViews are working 100%, and the Kendo ListView is working properly on the page (the ListView refreshes with the updated data).
My problem is that an IEnumerable of the view model is being passed to the ActionResult (with a null value) instead of just a single instance of the view model, and the DataSourceRequest is empty.
Here is the (redacted) code.
The view models (just the wrapper and view model for the ListView in question):
public class MainPersonViewModel
{
public MainPersonViewModel(){}
public int PersonId { get; set; }
public IEnumerable<DetailsViewModel> PersonDetails { get; set; }
public IEnumerable<AddressViewModel> Addresses { get; set; }
public IEnumerable<PersonGroupingViewModel> MemberOf { get; set; }
}
public class DetailsViewModel
{
public DetailsViewModel(){}
public int PersonId { get; set; }
public string Name { get; set; }
public string WorkingTitle { get; set; }
}
The Kendo ListView template:
#model Staff.ViewModels.MainPersonViewModel
<script type="text/x-kendo-tmpl" id="personDetailsTemplate">
<table>
<tr>
<td>Name: </td><td>${Name}</td>
</tr>
<tr>
<td>Working Title: </td><td>${Title}</td>
</tr>
<tr>
<td colspan="2">
<div class="edit-buttons">
<a class="k=button k-button-icontext k-edit-button" href="\\#"><span class="k-icon k-edit"></span>Edit</a>
</div>
</td>
</tr>
</table>
</script>
And the Kendo control itself:
#(Html.Kendo().ListView<Staff.ViewModels.DetailsViewModel>(Model.PersonDetails)
.Name("personDetailsList")
.TagName("div")
.ClientTemplateId("personDetailsTemplate")
.Editable()
.DataSource(ds => ds
.Model(m =>
{
m.Id(f => f.PersonId);
m.Field(f => f.Name);
m.Field(f => f.WorkingTitle);
}
)
.Read(read => read.Action("ViewPersonDetails", "Staff", new {id = Model.PersonId}))
.Update(update => update.Action("UpdatePersonDetails", "Staff"))
)
)
The ActionResult called by the Listview in the controller is as follows:
public class StaffController : Controller
{
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdatePersonDetails([DataSourceRequest] DataSourceRequest request, IEnumerable<DetailsViewModel> toUpdate)
{
//update code here
return Json(ModelState.ToDataSourceResult());
}
}
Finally the editor template (located in Views\Staff\EditorTemplates):
#model Staff.ViewModels.DetailsViewModel
<div>
<table>
<tr>
<td>#Html.LabelFor(m => m.NameFirst)</td>
<td>#Html.EditorFor(m => m.NameFirst)</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.NameLast)</td>
<td>#Html.EditorFor(m => m.NameLast)</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.Title)</td>
<td>#Html.EditorFor(m => m.Title)</td>
</tr>
<tr>
<td colspan="2">
<div class="edit-buttons">
<a class="k-button k-button-icontext k-update-button" href="\\#"><span class="k-icon k-update"></span>Save</a>
<a class="k-button k-button-icontext k-cancel-button" href="\\#"><span class="k-icon k-cancel"></span>Cancel</a>
</div>
</td>
</tr>
</table>
</div>
Since the ListView seems to be refreshing I don't think it's necessarily a problem with it or the DataSource on the page, so I'm leaning towards some detail (i.e. limitation) with the editor template that I'm missing. Any thoughts?
Sorry for the long post, and any help would be greatly appreciated!

Get Value of Property (List<long>) in Post Action in ASP.NET MVC3

This is My model:
public class MyModel
{
public List<long> NeededIds { get; set; }
public string Name { get; set; }
}
My Controllers:
public ActionResult Create()
{
MyModel model = new MyModel();
model.NeededIds = new List<long> { 1, 2, 3, 4 };
return View(model);
}
[HttpPost]
public ActionResult Create(MyModel model)
{
string name = model.Name;
List<long> ids = model.NeededIds;
return RedirectToAction("Index");
}
And View:
#model TestMVC.Models.MyModel
#using(Html.BeginForm()) {
<table>
<thead>
<tr>
<th>
Id
</th>
</tr>
</thead>
<tbody>
#foreach(long id in Model.NeededIds) {
<tr>
<td>
#id
</td>
</tr>
}
</tbody>
</table>
#Html.ValidationSummary(true)
<fieldset>
<legend>MyModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
I set NeededIds in Get action and in the view I can see NeededIds. I also need it in Post action, but in post action the NeededIds is always null. How can I get the property value in post action when I set it in get action? What is your suggestion?
You are not posting your NeededIds back to the server. In order to get this working you can add them as hidden fields in a for loop inside the form:
#for (int i = 0; i < Model.NeededIds.Count(); i++) {
#Html.HiddenFor(model => model.NeededIds[i])
}
if you are using layout page than simply remove the form tag from the layout page.
in addition to the answer by Yakimych
you have kept the ids as constant.. this means two things
1. you can use arrays in place of list
2.you can just save the ids list/array in TempData and retrive it back from there when POST happens
you can do this like this
in your GET handler
TempData.Add("ids",idArray);
in your POST handler
var idArray = (long[])TempData["ids"];

Resources