error while posting pagedlist from view to the controller - asp.net-mvc

I've an indexed page in MVC with data that displays in a table format from the database and using paging. I want to edit only one column of the table. Can I post the paging list to the controller for editing. If so how?
I'm able to edit with normal list getting error while passing PagedList
--- this is my index page----
#model PagedList.IPagedList<emp_prac.Models.Employee>
#using PagedList.Mvc;
#*#model List<emp_prac.Models.Employee>*#
#using (Html.BeginForm("UpdateOrder", "Employee", FormMethod.Post))
{
Html.AntiForgeryToken();
Html.EditorForModel();
ViewBag.Title = "Employee Details";
<h2>Employee Details</h2>
<p>
#Html.ActionLink("Create New", "InsertEmployee")
</p>
<table class="table">
<thead>
<tr>
<th>Edit</th>
<th>Delete</th>
<th>Name</th>
<th>Email</th>
<th>Phone No</th>
<th>Salary</th>
<th>Joining Date</th>
<th>PDF</th>
<th>Status</th>
<th>Order</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>#Html.ActionLink("Edit", "EditEmployee", new { id = Model[i].emp_id }) </td>
<td>#Html.ActionLink("Delete", "DeleteEmployee", new { id = Model[i].emp_id }, new { onclick = "return confirm('Are you sure you want to delete?');", #class = "btn-btn-default" }) </td>
<td>#Html.DisplayFor(model => model[i].emp_name)</td>
<td>#Html.DisplayFor(model => model[i].emp_email)</td>
<td>#Html.DisplayFor(model => model[i].emp_phone_no)</td>
<td>#Html.DisplayFor(model => model[i].emp_salary)</td>
<td>#Html.DisplayFor(model => model[i].emp_joining_date)</td>
<td>#Html.ActionLink("PDF", "UploadPdf", new { id = Model[i].emp_id }) </td>
<td>#(Html.DisplayFor(model => model[i].emp_status).ToString() == "1" ? "Active" : "Inactive")</td>
<td>#Html.TextBoxFor(model => model[i].emp_order, new { style = "width: 35px" })</td>
<td>#Html.HiddenFor(model => model[i].emp_id)</td>
</tr>
}
</tbody>
</table>
<button type="submit" value="Order" onclick="location.href='#Url.Action("UpdateOrder","Employee")'">Order</button>
}
<br />
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index", new { page }))`
---This is my controller action method---
[HttpPost]
public ActionResult UpdateOrder(PagedList<Employee> obj_view)
{
foreach (var abc in obj_view)
{
Employee obj = new Employee();
obj.emp_order = abc.emp_order;
obj.emp_id = abc.emp_id;
obj.Mode = "O";
Employee.InsertUpdateEmployee(obj);
}
return RedirectToAction("Index");
}

I looked deeply into your code , as per my point of view, below line may cause the error.
**<button type="submit" value="Order" onclick="location.href='#Url.Action("UpdateOrder","Employee")'">Order</button>
}**
Reason:
When you post the data through the form post, you no need to specify the onclick in the submit button
Solution:
Just replace the above line with simple submit button like this
**<input type="submit" value="Order" class="btn btn-default" />**
And see in the button click event whether you get the data or not using breakpoint.
Hope you will surely get the data now , kindly let me know your thoughts or feedbacks
Thanks
Karthik

Related

How to pass a data from an existing razor view as the parameter into a controller to load the new razor view

I am new to asp.net mvc, I have my main razor page Index with a button Edit Assessment and I don't know how to pass whatever id which my Index page have.
Right now I am passing a default value id = "2" as my parameter but this shouldn't be as the Index may contain any id depending on the selected record
Here is my code snippet from my Index page
<form asp-controller="Assessments" asp-action="Index" method="get">
<p>
<input type="button" class="btn btn-primary btn-lg float-right"
value="Edit Assessment"
onclick="location.href='#Url.Action("EditAssessment", "Assessments", new
{ id = "2" })'" />
</p>
</form>
....
<table class="table">
<thead>
<tr>
<th>
ID
</th>
....
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
....
</tr>
}
</tbody>
</table>
I would like to update the id = "2" into id = "Id from my model"
this is issue has been resolved.
I have updated my controller and added the ViewData["ProfileId"] = id;
public async Task<IActionResult> Index(
int? id,
int? pageNumber,
int pageSize)
{
...some codes here
var dataDividendToolContext = _context.Assessment
.Include(a => a.AsIs)
.Include(a => a.Profile)
.Include(a => a.Question)
.Include(a => a.Vision)
.Where(a => a.ProfileId == id);
...some codes here
ViewData["ProfileId"] = id;
...some codes here
}
On my CSHTML button I passed the ViewData["ProfileId"] as my parameter as seen below.
<input type="button" class="btn btn-primary btn-lg float-right" value="Edit
Assessment" onclick="location.href='#Url.Action("EditAssessment", "Assessments", new
{ id = ViewData["ProfileId"] })'" />

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

jquery post to asp.net mvc controller

I have these two controller actions:
public ActionResult Index(string search, int? page)
{
return View(db.powners.Where(x => x.petowner.StartsWith(search) || search == null).OrderBy(x => x.petowner).ToList().ToPagedList(page ?? 1, 5));
}
public ActionResult Ownerfind(string search, int? page)
{
return View(db.powners.Where(x => x.petowner.StartsWith(search) || search == null).OrderBy(x => x.petowner).ToList().ToPagedList(page ?? 1, 5));
}
And this json method also:
public JsonResult Getowner(int nownerid)
{
OwnerEntities owner = new OwnerEntities();
var existingCust = owner.powners.Single(p => p.ownerid == nownerid);
return Json(existingCust);
}
Index view:
#model PagedList.IPagedList<Mvc4test2.Models.powner>
#using PagedList.Mvc;
#using PagedList;
#{
ViewBag.Title = "Index";
}
<link href="../../Content/PagedList.css" rel="stylesheet" type="text/css" />
<div style="font-family:Arial">
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<p>
#using (#Html.BeginForm("Index", "owner", FormMethod.Get))
{
<b>Search</b>#Html.TextBox("search")<input type="submit" value="search" />
}
</p>
<table id="ownertable">
<tr>
<th>
#Html.DisplayNameFor(model => model.First().petowner)
</th>
<th>
#Html.DisplayNameFor(model => model.First().ostreet)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ownerid)
</td>
<td>
#Html.DisplayFor(modelItem => item.petowner)
</td>
<td>
#Html.DisplayFor(modelItem => item.ostreet)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ownerid }) |
#Html.ActionLink("Details", "Details", new { id=item.ownerid }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ownerid })
</td>
</tr>
}
</table>
#Html.PagedListPager(Model, page=>Url.Action("Index", new{page, search=Request.QueryString["search"]}), new PagedListRenderOptions(){Display=PagedListDisplayMode.IfNeeded, DisplayPageCountAndCurrentLocation=true,MaximumPageNumbersToDisplay=5})
Ownerfind view:
#model PagedList.IPagedList<Mvc4test2.Models.powner>
#using PagedList.Mvc;
#using PagedList;
#{
ViewBag.Title = "Index";
}
<link href="../../Content/PagedList.css" rel="stylesheet" type="text/css" />
<div style="font-family:Arial">
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<p>
#using (#Html.BeginForm("ownerfind", "owner", FormMethod.Get))
{
<b>Search</b>#Html.TextBox("search")<input type="submit" value="search" />
}
</p>
<p>
hello
</p>
<table id="ownertable">
<tr>
<th>
#Html.DisplayNameFor(model => model.First().petowner)
</th>
<th>
#Html.DisplayNameFor(model => model.First().ostreet)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ownerid)
</td>
<td>
#Html.DisplayFor(modelItem => item.petowner)
</td>
<td>
#Html.DisplayFor(modelItem => item.ostreet)
</td>
</tr>
}
</table>
#Html.PagedListPager(Model, page=>Url.Action("ownerfind","owner", new{page, search=Request.QueryString["search"]}), new PagedListRenderOptions(){Display=PagedListDisplayMode.IfNeeded, DisplayPageCountAndCurrentLocation=true,MaximumPageNumbersToDisplay=5})
</div>
Jquery segment:
$("#ownertable td:nth-child(1)").click(function (event) {
event.preventDefault();
var $td = $(this).closest('tr').children('td');
var currentid = $.trim($td.eq(0).text());
alert("hi:" + currentid);
$.ajax({
url: 'owner/Getowner',
type: 'POST',
data: 'nownerid=' + currentid,
dataType: "json",
success: function (result) {
alert("hello");
//alert(result.petowner);
opener.$('input#ownerid').val(result.ownerid);
opener.$('#petowner').val(result.petowner);
opener.$('input#ostreet').val(result.ostreet);
self.close();
}
});
});
Here's the problem:
If I use the first controller action public ActionResult Index(string search, int? page), then I get the json result as expected. However if I use the second controller action
public ActionResult Ownerfind(string search, int? page) then the I donot get a json result back.
Both controller actions work on screen, and I get the alert("hi:" + currentid);
But I only get a json result if I use click on the table used in the Index view.
Why isn't the ownerfind view working with jquery? It displays correctly just no json result.
I want seperate view, because one will be a lookup and another a regular for adding and editing.
Add [HttpPost] attribute to Getowner action from Contoller
And return from get owner something like this:
return Json(new { Data = existingCust });

How to pass a list of objects to a [HTTPPost]controller parameter, in 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.

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