how to get data using #Ajax.ActionLink() in ASP.net MVC - asp.net-mvc

i want get data using #Ajax.ActionLink() method. i have tried in the following way
Create.chtml
function UpdatePoDetails() {
document.getElementById("poSearchbtn").href = "/MaterialReceivePO/SearchPO?searchID=" + document.getElementById('POID').value
}
#using (Ajax.BeginForm(new AjaxOptions
{
UpdateTargetId = "searchData",
LoadingElementId = "loading"
}
))
{
<input id="POName" type="text" />
#Ajax.ActionLink("Search", "SearchPO", null, new AjaxOptions
{
UpdateTargetId = "PoDetailsDiv",
HttpMethod = "GET"
},
new
{
onclick = "UpdatePoDetails()" ,
id = "poSearchbtn"
}
)
}
#using (Ajax.BeginForm(new AjaxOptions
{
UpdateTargetId = "MainBody",
LoadingElementId = "loading"
}))
{
<div id="PoDetailsDiv">
</div>
}
Controller method
public ActionResult SearchPO(string searchID)
{
int id = int.Parse(searchID);
List<PurchaseOrderDetailsModel> podetails = (
from c in po.GetPoListDetails(id)
select new PurchaseOrderDetailsModel()
{
PoDetailsID = c.PoDetailsID,
ItemID = c.ItemID.Value,
Quantity = c.Quantity,
UnitPrice = c.UnitPrice,
TotalPrice = c.TotalPrice,
DiscountPer = c.DiscountPer,
FinalPrice = c.FinalPrice,
CurrencyID = c.CurrencyID,
ProductID = c.ItemID.Value,
ProductName = c.ProductName,
ProductCode = c.ProductCode,
Description = c.Description
}
).ToList();
return View("SearchPO",podetails);
}
SearchPO.chtml
#model IEnumerable<ERP_Web.Areas.Inventory.Models.PurchaseOrderDetailsModel>
<table class="grid-table">
<tr>
<th>
Product Name
</th>
<th>
Code
</th>
<th>
Quantity
</th>
<th>
Unit price
</th>
<th>
Total
</th>
<th>
Discount
</th>
<th>
Final price
</th>
<th>
Receive Quantity
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ProductName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ProductCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.Quantity)
</td>
<td>
#Html.DisplayFor(modelItem => item.UnitPrice)
</td>
<td>
#Html.DisplayFor(modelItem => item.TotalPrice)
</td>
<td>
#Html.DisplayFor(modelItem => item.DiscountPer)
</td>
<td>
#Html.DisplayFor(modelItem => item.FinalPrice)
</td>
<td>
#Html.TextBox("reQuantity");
</td>
</tr>
}
</table>
the poblem is when click on the Ajax link the it goes to the Controller. the controller code executes well but at the end to does not Call the SearchPO View when returning. What is wrong in my Code or what i missing. Any help??

#Ajax.ActionLink("Search", "SearchPO", null,
new AjaxOptions{UpdateTargetId = "PoDetailsDiv",HttpMethod = "GET" },new {id = "poSearchbtn"})
I don't understand why you need this onclick = "UpdatePoDetails()"
public ActionResult SearchPO(string searchID)
{
//Do your logic here
//Build Mark-up of the result
string GeneratedMarkUp = BuildMarkUpFOrtheResult();
return Json(GeneratedMarkUp);
}

Related

How i can send list of data from two tables to view?

I'm work in asp mvc application database first a broach So i have two tables Employee and Branch and i need to send list to view with Employee name and branch name that's my controller code
public PartialViewResult List()
{
List<Employee> emp;
using (var contxt = new EnglisCenterEntities())
{
var query = contxt.Employee.ToList();
emp = query;
}
return PartialView(emp);
}
and my view code is
#model IEnumerable<Insert.Models.Employee>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.EmpName)
</th>
<th>
#Html.DisplayNameFor(model => model.Phone)
</th>
<th>
#Html.DisplayNameFor(model => model.Username)
</th>
<th>
#Html.DisplayNameFor(model => model.Branches.BranchName)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.EmpName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Phone)
</td>
<td>
#Html.DisplayFor(modelItem => item.Username)
</td>
<td>
#Html.DisplayFor(modelItem => item.Branches.BranchName)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.IdEmp }) |
#Html.ActionLink("Details", "Details", new { id=item.IdEmp }) |
#Html.ActionLink("Delete", "Delete", new { id=item.IdEmp })
</td>
</tr>
}
But it doesn't work so how i can send branch name with employee data
Here is :
public PartialViewResult List()
{
List<Employee> emp;
using (var contxt = new EnglisCenterEntities())
{
var brands = contxt.Employee.Include("Branches").ToList();
// var query = contxt.Employee.ToList();
emp = brands;
}
return PartialView(emp);
}
Thanks guys :)

Modifying the text color and background color of a table

I no longer have a question as I figured out how to do it
Index.cshtml
#model IEnumerable<ContactManager.Models.Contacts>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2></h2>
#using (Html.BeginForm()) {
<p>#Html.TextBox("SearchString")
<input type="submit" value="Search" /></p>
}
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstName)
</th>
<th>
#Html.DisplayNameFor(model => model.LastName)
</th>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<th>
#Html.DisplayNameFor(model => model.City)
</th>
<th>
#Html.DisplayNameFor(model => model.State)
</th>
<th>
#Html.DisplayNameFor(model => model.Zip)
</th>
<th>
#Html.DisplayNameFor(model => model.Phone)
</th>
<th>
Modify
</th>
</tr>
#foreach (var item in Model) {
var lncolor = "white" ;
var zipcolor = "black";
switch (item.LastName) {
case "Whited":
lncolor = "yellow";
break;
default:
lncolor = "white";
break;
}
if (item.ID % 2 == 0) {
zipcolor = "red";
} else {
zipcolor = "black";
}
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td bgcolor="#lncolor">
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#Html.DisplayFor(modelItem => item.State)
</td>
<td>
<font color="#txtcolor">
#Html.DisplayFor(modelItem => item.Zip)
</font>
</td>
<td>
#Html.DisplayFor(modelItem => item.Phone)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
Relative part of my Controller
private ContactsDBContext db = new ContactsDBContext();
// GET: Contacts
public ActionResult Index(string searchString)
{
var contacts = from c in db.Contact
select c;
if (!String.IsNullOrEmpty(searchString)) {
contacts = contacts.Where(s => s.FirstName.Contains(searchString) || s.LastName.Contains(searchString) || s.Address.Contains(searchString)
|| s.City.Contains(searchString) || s.State.Contains(searchString) || s.Zip.Contains(searchString) || s.Phone.Contains(searchString));
}
//return View(db.Contact.ToList());
return View(contacts);
}
I managed to figured out a way to accomplish what I wanted to do with this. I have updated the code as well to refelct on what I have done. I am not sure it is the most elegant way to accomplish this so if anyone has any better suggestions I am all ears.
Writing any kind of logic in view page is highly depreciated in MVC pattern. You can do it by using viewmodel. Here is the steps.
First create an appropriate view model for model contact.
public class ContactViewModel
{
public string FirstName{ get; set; }
public string LastName{ get; set; }
public string Address{ get; set; }
public string City{ get; set; }
public string State{ get; set; }
public string Zip{ get; set; }
public string Phone{ get; set; }
public string LastNameBgcolor{ get; set; }
public string FontColor{ get; set; }
}
In controller:
private ContactsDBContext db = new ContactsDBContext();
// GET: Contacts
public ActionResult Index(string searchString)
{
var contacts = from c in db.Contact
select c;
if (!String.IsNullOrEmpty(searchString)) {
contacts = contacts.Where(s => s.FirstName.Contains(searchString) || s.LastName.Contains(searchString) || s.Address.Contains(searchString)
|| s.City.Contains(searchString) || s.State.Contains(searchString) || s.Zip.Contains(searchString) || s.Phone.Contains(searchString));
}
//return View(db.Contact.ToList());
List<ContactViewModel> ContactViewModels= new List<ContactViewModel>();
foreach(var contact in contacts){
ContactViewModel cvm= new ContactViewModel();
cvm.FirstName=contact.FirstName;
cvm.LastName=contact.LastName;
if(contact.LastName=="Whited"){
cvm.LastNameBgcolor="yellow";
}
else{
cvm.LastNameBgcolor="white";
}
cvm.Address=contact.Address;
cvm.City=contact.City;
cvm.State=contact.State;
cvm.Zip=contact.Zip;
cvm.Phone=contact.Phone;
if (contact.ID % 2 == 0) {
cvm.FontColor = "red";
} else {
cvm.FontColor = "black";
}
ContactViewModels.Add(cvm);
}
return View(ContactViewModels);
}
In view page:
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td bgcolor="#model.LastNameBgcolor">
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#Html.DisplayFor(modelItem => item.State)
</td>
<td>
<font color="#model.FontColor">
#Html.DisplayFor(modelItem => item.Zip)
</font>
</td>
<td>
#Html.DisplayFor(modelItem => item.Phone)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
Hope this will help.

Add Search Engine into MVC Music Store

i'm trying to add search the title plus genre drop down list inside store in mvc music store. here's the procedure i've done
firstly i'v added the below code into the StoreManagere controller
public ActionResult SearchIndex(string musicGenre, string searchString)
{
var GenreLST = new List<string>();
var GenreQry = from d in db.Genres
orderby d.Name
select d.Name;
GenreLST.AddRange(GenreQry.Distinct());
ViewBag.movieGenre = new SelectList(GenreLST);
var musics = from m in db.Albums.Include(a => a.Genre).Include(a => a.Artist)
select m;
if (!string.IsNullOrEmpty(searchString))
{
musics = musics.Where(s => s.Title.Contains(searchString));
}
if (string.IsNullOrEmpty(musicGenre))
return View(musics);
else
{
return View(musics.Where(x => x.Genre.Name == musicGenre));
}
}
and the below code inside search index view page
#model IEnumerable<MvcMusicStore.Models.Album>
#{
ViewBag.Title = "SearchIndex";
}
<h2>SearchIndex</h2>
<p>
#Html.ActionLink("Create New", "Create")
#using (Html.BeginForm()) {
<p>Genre : #Html.DropDownList("musicGenre", "All")
Title : #Html.TextBox("searchString")
<input type="submit" value="Filetr" /></p>
}
</p>
<table>
<tr>
<th>
Genre
</th>
<th>
Artist
</th>
<th>
Title
</th>
<th>
Price
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Genre.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Artist.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.AlbumId }) |
#Html.ActionLink("Details", "Details", new { id=item.AlbumId }) |
#Html.ActionLink("Delete", "Delete", new { id=item.AlbumId })
</td>
</tr>
}
</table>
but i get this error
There is no ViewData item of type 'IEnumerable' that has the key 'musicGenre'.
You saved your genre list in ViewBag.movieGenre not musicGenre. That's why it is not working.

Delete Action doesn't get called

On click of delete link i want to call DeleteConfirmed Method in my Student Controller.
Student Controller Code
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Student student = db.Students.Find(id);
db.Students.Remove(student);
db.SaveChanges();
return RedirectToAction("Index");
}
Index.cshtml has delete link (last line of code) on click of which i want the DeleteConfirmed to be called but the below expects delete.cshtml to be present.I don't want to show delete view and just want the delete to happen asynhronously.
#model IEnumerable<SMS.Model.Student>
#{
ViewBag.Title = "Student";
}
<h2>Student</h2>
#using (Html.BeginForm()) {
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.RegistrationNo)
</th>
<th>
#Html.DisplayNameFor(model => model.FirstName)
</th>
<th>
#Html.DisplayNameFor(model => model.MiddleName)
</th>
<th>
#Html.DisplayNameFor(model => model.LastName)
</th>
<th>
#Html.DisplayNameFor(model => model.DateofBirth)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.RegistrationNo)
</td>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.MiddleName)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateofBirth)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Details", "Details", new { id=item.Id }) |
#Ajax.ActionLink("Delete", "Delete", new { id = item.Id },new AjaxOptions { HttpMethod = "Post"})
</td>
</tr>
}
}
Inside the view instead of
#using (Html.BeginForm())
You should have
#using (Html.BeginForm("DeleteConfirmed", "YourControllerName"))
If won't work, removing ActionName("Delete") should do the trick.
Let me know if that was of help.

MVC 3 model item passed into dictionary error

I get this error and i don't understand why:
The model item passed into the dictionary is of type 'Devart.Data.Linq.DataQuery`1[CHRContext.WIKIIDEE]', but this dictionary requires a model item of type 'CHRContext.WIKIREPARTO'.
method from model
public IQueryable<WIKIIDEE> GetIdeasByDeptID(int id)
{
var query = from i in db.WIKIIDEEs
where i.IDREPARTO == id
select i;
return query;
}
method from controller
public ActionResult List(int id)
{
try
{
IdeeRepository ideeRepo = new IdeeRepository();
IQueryable<WIKIIDEE> list = ideeRepo.GetIdeasByDeptID(id);
return View(list);
}
catch (Exception Ex)
{
return View("Error");
}
}
and view
#model IEnumerable<CHRContext.WIKIIDEE>
#{
ViewBag.Title = "List";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>List</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
IDREPARTO
</th>
<th>
DATAINSERIMENTO
</th>
<th>
DESCRIZIONE
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.IDREPARTO)
</td>
<td>
#Html.DisplayFor(modelItem => item.DATAINSERIMENTO)
</td>
<td>
#Html.DisplayFor(modelItem => item.DESCRIZIONE)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Details", "Details", new { id = item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
</table>
I ran into a very similar issue and was able to work around it. You can see how, here in my answer: The model item passed into the dictionary is of type A, but this dictionary requires a model item of type B

Resources