jquery post to asp.net mvc controller - asp.net-mvc

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 });

Related

error while posting pagedlist from view to the controller

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

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

MVC4 Filtering with checkboxes

I have created create function in my controller which display all genres in checkoxes like this:
Controller:
public ActionResult Create()
{
var db = new MainDatabaseEntities();
var viewModel = new ANIME
{
GENRES = db.GENRES.Select(c => new { ID_GE = c.ID_GE, GENRE = c.GENRE, isSelected = false }).ToList().Select(g => new GENRES
{
ID_GE = g.ID_GE,
GENRE = g.GENRE,
isSelected = false
}).ToList()
};
return View(viewModel);
}
View:
#model AnimeWeb.Models.ANIME
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<table>
<tr>
<td class="lefttablecontent" id="top">
<div class="editor-label">
#Html.HiddenFor(model => model.ID_AN)
</div>
<div class="editor-label">
Original title
</div>
<div class="editor-field">
#Html.EditorFor(model => model.TITLE_OR)
#Html.ValidationMessageFor(model => model.TITLE_OR)
</div>
<div class="editor-label">
English title
</div>
<div class="editor-field">
#Html.EditorFor(model => model.TITLE_EN)
#Html.ValidationMessageFor(model => model.TITLE_EN)
</div>
<div class="editor-label">
Genres
</div>
<div class="editor-list">
#Html.EditorFor(model => model.GENRES)
#Html.ValidationMessageFor(model => model.GENRES)
</div>
</td>
<td class="righttablecontent" id="top">
<p>
<input type="submit" value="Create" />
</p>
</td>
</tr>
</table>
}
}
EditorTemplate for Genres:
#model AnimeWeb.Models.GENRES
#Html.HiddenFor(model => model.ID_GE)
#Html.HiddenFor(model => model.GENRE)
<table>
<tr>
<td class=" right">
#Html.EditorFor(model => model.isSelected)
</td>
<td>
#Html.LabelFor(model => model.isSelected, Model.GENRE)
</td>
</tr>
</table>
Now I would like to display the same template with all genres and use it for filtering in index, but I'm not sure how to do this.
Controller:
public ActionResult Index(string sortOrder, string currentFilter, int? page)
{
using (var db = new MainDatabaseEntities())
{
ViewBag.CurrentSort = sortOrder;
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var anime = from s in db.ANIME.Include("GENRES")
select s;
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(anime.ToPagedList(pageNumber, pageSize));
}
}
View:
#model PagedList.IPagedList<AnimeWeb.Models.ANIME>
#using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
#{
ViewBag.Title = "Index";
}
<p>
#if (Roles.IsUserInRole("Administrator"))
{
#Html.ActionLink("Create New", "Create")
}
</p>
#foreach (var item in Model) //
{ //
#Html.EditorFor(modelItem => item.GENRES); // I'm not sure about this line
} //
<table>
<tr>
<th>
Anime
</th>
<th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.ActionLink(item.TITLE_OR, "Details", new { id = item.ID_AN })
</td>
</tr>
}
</table>
<br />
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
When I try to display it with #Html.EditorFor(modelItem => item.GENRES) it displays only genres that are selected within each anime but I need all genres to filter with them. I'm not even sure is this a good way to make it. Any suggestions?

How to update Partial View without full replacement

I have this partial view. This works, ie, when the user clicks the button, an ajax trip is made to the server, and it updates the partial view and it comes down and replaces the current div with the updated Div and shows the Promo Message.
However, it seems there should be a better way to do this. In other words, is it necessary to replace the entire partial view? Isn't there a way to send just the data up to the server, and then update just the message when it gets back, like maybe via a JSON call?
Controller:
public ActionResult ApplyPromoCode(OrderViewModel orderViewModel) {
orderViewModel.PromoMessage = "Promo has been applied";
return PartialView("PromoPartial", orderViewModel);
}
Partial View:
#model NTC.PropertySearch.Models.OrderViewModel
#using (Ajax.BeginForm("ApplyPromoCode", "OrderSummary", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "promo" }))
{
<div id="promo">
<table>
<td>
#Html.LabelFor(m => m.PromoCode)
</td>
<td>
#Html.TextBoxFor(m => m.PromoCode)
</td>
<td>
#Html.ValidationMessageFor(m => m.PromoCode)
</td>
<td>
<input type="submit" value="Apply Promo Code" />
</td>
<td>
#Html.DisplayFor(m=> m.PromoMessage)
</td>
</table>
</div>
}
you can do this to
Controller
public ActionResult ApplyPromoCode(OrderViewModel orderViewModel) {
//your processing code
return Content("Promo has been applied");
}
View
#model NTC.PropertySearch.Models.OrderViewModel
#using (Ajax.BeginForm("ApplyPromoCode", "OrderSummary", new AjaxOptions { UpdateTargetId = "pcode" }))
{
<div id="promo">
<table>
<td>
#Html.LabelFor(m => m.PromoCode)
</td>
<td>
#Html.TextBoxFor(m => m.PromoCode)
</td>
<td>
#Html.ValidationMessageFor(m => m.PromoCode)
</td>
<td>
<input type="submit" value="Apply Promo Code" />
</td>
<td>
<div id="pcode"></div>
</td>
</table>
</div>
}
Instead of returning a PartialView you can always return a JSON object/array or some XML and use jQuery/JavaScript on your callback function to update the values of your input fields.
Here's an example of some code I use to return JSON from a Controller:
public ActionResult CurrentTags(int entityID)
{
Entity entity = db.Entity.Find(entityID);
var tags = from tag in entity.Tag
select new
{
id = tag.Name,
text = tag.Name
};
return this.Json(tags, JsonRequestBehavior.AllowGet);
}

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.

Resources