How to pass a list of objects to a [HTTPPost]controller parameter, in ASP.Net MVC? - asp.net-mvc

i have the next view:
#model IEnumerable<L5ERP.Model.BLL.BusinessObjects.MTR_MonthlyTransfer>
#using (Html.BeginForm("ExpenseMonthlyTransferProcessing", "BudgetTransfer", Model.ToList())){
<table class ="divTable">
<tr>
<th>Transferir</th>
<th>
Clave
</th>
<th>
Monto
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.CheckBoxFor(x => item.MTR_Bool, new { #class = "checkMTR", #checked = "checked" })
</td>
<td>
#Html.TextBoxFor(x => item.MTR_Key, new {#class = "longInput" })
</td>
<td>
#String.Format("{0:F}", item.MTR_Amount)
</td>
</tr>
}
</table>
}
and my controller like this
[HttpPost]
public ActionResult ExpenseMonthlyTransferProcessing(List<MTR_MonthlyTransfer> lstMtr)
{ return View(lstMTR); }
But when i do the post my list is null, how can i send my list through the submit button ?

You should change the #model to an array (L5ERP.Model.BLL.BusinessObjects.MTR_MonthlyTransfer[]) or something else that implements IList<>:
#model L5ERP.Model.BLL.BusinessObjects.MTR_MonthlyTransfer[]
#for (var i = 0; i < Model.Length; i ++) {
<tr>
<td>
#Html.CheckBoxFor(x => Model[i].MTR_Bool, new { #class = "checkMTR", #checked = "checked" })
</td>
<td>
#Html.TextBoxFor(x => Model[i].MTR_Key, new {#class = "longInput" })
</td>
<td>
#String.Format("{0:F}", item.MTR_Amount)
</td>
</tr>

receive a FormCollection and parse the items in it manually
Use F12 to check the post in your navigator to see if it are sending the content you expected.

Related

MVC 5 get value of CheckBox Checked in controller with Ajax.BeginForm

I use MVC 5 and I try to get the value of the checkbox checked in the controller but so far it always return null.
Here is my code:
In View
#using (Ajax.BeginForm("Delete",
"User",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "table",
OnSuccess = "Success",
OnFailure = "Fail"
}))
{
Add
<button type="submit">Delete</button>
<div id="table">
#{Html.RenderPartial("_UserTable", Model);
</div>
}
My Partial View
<table>
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox" namespace="userCheck" value="#Html.DisplayFor(modelItem => item.UserName)"/>
</td>
<td>
#Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
</tr>
}
</tbody>
</table>
And My Controller
public ActionResult
Delete(string[] userCheck)
{
for (int ix = 0; ix < userCheck.Length; ix++)
{
// do something with userCheck[ix]
}
return Index();
}
My button works and go to the Delete Action but userCheck is always null.
How can I get the value of the multiple checkbox?
Thanks

How to Delete Multiple Record using Checkbox?

I'm creating a project for my institute. Using Asp.net MVC, I need multiple delete option with selected checkbox.
I have added a check in my view, but not delete multiple Raw. I don't want to use third party plugin. Please help me.
<table class="table table-striped table-condensed table-bordered">
<tr>
<th>
Select
</th>
<th>
#Html.ActionLink("Book Id", "Index", new { sortOrder = ViewBag.IdSortParm, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink("Title", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink("Date", "Index", new { sortOrder = ViewBag.DateSortParm, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
Price
</th>
<th>
Category
</th>
<th class="text-center">
Photo
</th>
<th>
User
</th>
<th>Edit</th>
<th>Delete</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox" name="deleteInputs" value="#item.BookId" />
</td>
<td>
#Html.DisplayFor(modelItem => item.BookId)
</td>
<td>
#Html.ActionLink(item.BookTitle, "Details", new
{
id = item.BookId
})
</td>
<td>
#Html.DisplayFor(modelItem => item.PublishDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.DisplayFor(modelItem => item.Category)
</td>
<td class="text-center">
<img class="img-thumbnail" width="50" height="50" src="~/ContentImages/Full/#item.Photo" />
</td>
<td>
#Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.BookId })
</td>
<td>
#Html.ActionLink("Delete", "Delete", new { id = item.BookId })
</td>
</tr>
}
</table>
This could be a way to achieve it:
First embed the table within a named form, that executes the batch delete action, like so:
#{ Html.BeginForm("BatchDelete", "Book", FormMethod.Post, new { name = "tableForm" }); }
<table class="table table-striped table-condensed table-bordered">
<tr>
<th>
Select
</th>
<th>
#Html.ActionLink("Book Id", "Index", new { sortOrder = ViewBag.IdSortParm, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink("Title", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink("Date", "Index", new { sortOrder = ViewBag.DateSortParm, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
Price
</th>
<th>
Category
</th>
<th class="text-center">
Photo
</th>
<th>
User
</th>
<th>Edit</th>
<th>Delete</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox" name="deleteInputs" value="#item.BookId" />
</td>
<td>
#Html.DisplayFor(modelItem => item.BookId)
</td>
<td>
#Html.ActionLink(item.BookTitle, "Details", new
{
id = item.BookId
})
</td>
<td>
#Html.DisplayFor(modelItem => item.PublishDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.DisplayFor(modelItem => item.Category)
</td>
<td class="text-center">
<img class="img-thumbnail" width="50" height="50" src="~/ContentImages/Full/#item.Photo" />
</td>
<td>
#Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.BookId })
</td>
<td>
#Html.ActionLink("Delete", "Delete", new { id = item.BookId })
</td>
</tr>
}
</table>
<!-- Section for buttons -->
<div class="actions">
<a href="javascript:(function(){document.tableForm.submit();return void(0);})()">
Delete selected books
</a>
</div>
#{ Html.EndForm(); }
Note that after the table, before ending the form, I added a link that executes the submit of the form.
Now, on the controller side, asumming its name is "BookController":
public class BookController : Controller
{
// ...
[HttpPost]
public ActionResult BatchDelete(int[] deleteInputs)
{
// You have your books IDs on the deleteInputs array
if (deleteInputs != null && deleteInputs.Length > 0)
{
// If there is any book to delete
// Perform your delete in the database or datasource HERE
}
// And finally, redirect to the action that lists the books
// (let's assume it's Index)
return RedirectToAction("Index");
}
// ...
}
Notice that:
The first two parameter of the Html.BeginForm method, are the action name and controller name (without the "Controller" suffix).
The last parameter of the same method include the name of the form. The name is used in the javascript of the link, in order to indicate which form are you going to submit.
First, you need a different Id for each checkbox so you know which record is to be deleted. Second, if you implement "delete" as a link then the browser will perform a GET action instead of a POST. Assuming you are not using AJAX then you will need a form so you can POST to the controller action which handles the delete.

redirect to a action that expects value in other controller

I have a controller StepOfIdea,and this controller has a action like this :
StepOfIdeaRepository objStepOfIdearepository=new StepOfIdeaRepository();
public ActionResult Index(int ideaId)
{
return View(objStepOfIdearepository.FindBy(i=>i.IdeaId==ideaId));
}
So i have another controller named idea and this controller has a view named index
#model IEnumerable<DomainClass.Idea>
#{
ViewBag.Title = "Index";
}
<h2>لیست</h2>
#if (User.IsInRole("User"))
{
<p>
#Html.ActionLink("ایده جدید", "Create", new {step = 1})
</p>
}
<table>
<tr>
#if (User.IsInRole("Admin"))
{
<th>
#Html.DisplayNameFor(model => model.User.Name)
</th>
}
<th>
#Html.DisplayNameFor(model => model.IdeaPersion)
</th>
<th>
#Html.DisplayNameFor(model => model.IdeaEnglish)
</th>
<th>
#Html.DisplayNameFor(model => model.IdeaResult)
</th>
<th>
#Html.DisplayNameFor(model => model.Date)
</th>
<th></th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
#if (User.IsInRole("Admin"))
{
<td>
#Html.DisplayFor(modelItem => item.User.Name) #Html.DisplayFor(modelItem => item.User.Name)
</td>
}
<td>
#Html.DisplayFor(modelItem => item.IdeaPersion)
</td>
<td>
#Html.DisplayFor(modelItem => item.IdeaEnglish)
</td>
<td>
#Html.DisplayFor(modelItem => item.IdeaResult)
</td>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td>
#Html.RenderAction("ویرایش","index", stepofidea, new { id=item.Id }) |
</td>
<td>
#Html.ActionLink("ویرایش", "Edit", new { id=item.Id }) |
#Html.ActionLink("نمایش", "Edit", new { id=item.Id }) |
#Html.ActionLink("حذف", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
In this line
#Html.RenderAction("ویرایش","index", ????, new { id=item.Id }) |
I want to redirect to index action of stepOfIdea controller and pass a value .But the above line doesn't work .
I think you confused some terms in translation to English, and what you are actually looking for is to create an Link that also passes a variable.
You can do this very simply, by:
#Html.ActionLink("ویرایش", "Index", "StepOfIdea", new { id = item.Id }, null)
This will create the HTML:
ویرایش

ASP.NET MVC join tables view result error

im trying to join two table and show the results in a strongly-typed list view in with columns from two tables,
public ActionResult OrderDetails(int id) {
var query = from o in db.OrderDetails
join a in db.Albums on o.AlbumId equals a.AlbumId
where o.OrderId == id
select new OrderDetail() {
OrderId = o.OrderId,
AlbumId = o.AlbumId,
Quantity = o.Quantity,
UnitPrice = o.UnitPrice,
Album = new Album {
Title = a.Title
}
};
return View(query);
}
Here is my view
#model IEnumerable<QWERK.OrderDetail>
#{
ViewBag.Title = "OrderDetails";
}
<h2>OrderDetails</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.OrderId)
</th>
<th>
#Html.DisplayNameFor(model => model.AlbumId)
</th>
<th>
#Html.DisplayNameFor(model => model.Quantity)
</th>
<th>
#Html.DisplayNameFor(model => model.UnitPrice)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.OrderId)
</td>
<td>
#Html.DisplayFor(modelItem => item.AlbumId)
</td>
<td>
#Html.DisplayFor(modelItem => item.Quantity)
</td>
<td>
#Html.DisplayFor(modelItem => item.UnitPrice)
</td>
<td>
#Html.DisplayFor(modelItem => item.Album.Title)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.OrderDetailId }) |
#Html.ActionLink("Details", "Details", new { id=item.OrderDetailId }) |
#Html.ActionLink("Delete", "Delete", new { id=item.OrderDetailId })
</td>
</tr>
}
</table>
But i keep getting a NotSupportedException
Im pretty sure im getting the error because im using the OrderDetails Model but how can i get around this to show multiple columns from different tables???? any help would be greatly appreciated...thanks

Why the value is changed after clicking the submit button?

I make one action method for 2 activities (new input and edit), and there is also only one
view to handle those activities.
But I don't understand no matter what activity happen, the action method always think it is a new input.
I learned that it because of the ID is always 0, but the problem is, when doing the edit, when in the view the ID is correct as the ID of the data, but when I click the submit button, the action method just see the 0 value of ID.
Here is the action method I used:
[HttpPost]
public ActionResult AddAssignment(SateliteSchedule SatSched)
{
var txt = "";
if (ModelState.IsValid)
{
if (SatSched.ID == 0)
{
db.SateliteSchedules.Add(SatSched);
txt = "{0} has been added!";
}
else
{
db.Entry(SatSched).State = EntityState.Modified;
txt = "{0} has been modified!";
}
db.SaveChanges();
Utility utl = new Utility();
TempData["message"] = string.Format(txt, utl.GetSateliteName(SatSched.SateliteID));
return RedirectToAction("FormAssignment");
}
else
{
ViewBag.Message = "ModelState is not Valid!";
return View("ErrorView");
}
}
And here is the view:
#using (Html.BeginForm("AddAssignment", "admin", FormMethod.Post))
{
#Html.ValidationSummary(true)
<table>
<tr>
<td>#Html.LabelFor(m => m.Tanggal)
</td>
<td>
#Html.EditorFor(m => m.Tanggal)
#Html.ValidationMessageFor(m => m.Tanggal)
</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.SateliteID)</td>
<td>
#Html.DropDownList("SateliteID", (IEnumerable<SelectListItem>)ViewBag.SatList, "--- Satelite ---")
#Html.ValidationMessageFor(m => m.SateliteID)
</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.WMOnDuty)</td>
<td>
#Html.DropDownList("WMOnDuty", (IEnumerable<SelectListItem>)ViewBag.WMList, "--- Worship Manager ---")
#Html.ValidationMessageFor(m => m.WMOnDuty)
</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.SMOnDuty)</td>
<td>#Html.EditorFor(m => m.SMOnDuty)</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.WLOnDuty)</td>
<td>#Html.EditorFor(m => m.WLOnDuty)</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.MLOnDuty)</td>
<td>#Html.EditorFor(m => m.MLOnDuty)</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.SoundMan)</td>
<td>#Html.EditorFor(m => m.SoundMan)</td>
</tr>
<tr>
<td valign=top>#Html.LabelFor(m => m.Note)</td>
<td>#Html.TextAreaFor(model => model.Note, new { #class = "memo-text" })</td>
</tr>
</table>
<div>
<input type="submit" value="Save" />
#Html.ActionLink("Kembali", "FormAssignment")
</div>
}
What should I check to fix this?
You have to have the Id as a hidden, so when you go in the method the model will have the id asigned to it (does it make sense?). try placing this in your form
#Html.HiddenFor(m => m.ID)

Resources