Delete Action doesn't get called - asp.net-mvc

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.

Related

asp.net get values from few textFields

i have a problem to collect the values in my text fields .
in each row on my screen i have a text field and the user should be add values there (you can see it from the picture)
exaple of my site
this is my html code:
#using (Html.BeginForm("Create", "User", FormMethod.Post))
{
#Html.AntiForgeryToken()
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.BarCode)
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Profit)
</th>
<th>
Amount
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.BarCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Profit)
</td>
<td>
<form action="/action_page.php">
Amount:
<input type="text" id="amountTag" name="Amount" maxlength="2" placeholder="0" size="4" runat="server" />
</form>
</td>
</tr>
}
<tr>
<td><input type="submit" value="Submit" class="btn btn-default" /></td>
</tr>
</table>
}
and my code is
// POST: User/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
/*Update the Database*/
// TODO: Add insert logic here
string x = Request.Form["amountTag"];
return RedirectToAction("Index");
}
catch
{
return View();
}
}
this code always get Null and i don't have idea why
This section will create a form inside existing form (nested forms), which is not a good way to bind the textbox:
<form action="/action_page.php">
Amount:
<input type="text" id="amountTag" name="Amount" maxlength="2" placeholder="0" size="4" runat="server" />
</form>
The correct way should be like this:
1) Create an int property of Amount in the same viewmodel class as BarCode, Name and Profit properties has.
public class ViewModelName
{
// required unique key for each rows
public int Id { get; set; }
// other 3 properties here
[DisplayName("Amount")]
public int Amount { get; set; }
}
2) Bind the model inside view with HTML helpers using for loop. Here you should add TextBoxFor helper for Amount property to let user input numeric value with HTML attributes you have previously:
#model IEnumerable<ViewModelClassName>
#using (Html.BeginForm("Create", "User", FormMethod.Post))
{
#Html.AntiForgeryToken()
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.BarCode)
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Profit)
</th>
<th>
Amount
</th>
</tr>
#for (int i = 0; i < Model.Count; i++)
{
#Html.HiddenFor(modelItem => modelItem[i].Id)
<tr>
<td>
#Html.DisplayFor(modelItem => modelItem[i].BarCode)
</td>
<td>
#Html.DisplayFor(modelItem => modelItem[i].Name)
</td>
<td>
#Html.DisplayFor(modelItem => modelItem[i].Profit)
</td>
<td>
#* Amount *#
#Html.LabelFor(modelItem => modelItem[i].Amount)
#Html.TextBoxFor(modelItem => modelItem[i].Amount, new { maxlength = 2, ... })
</td>
</tr>
}
<tr>
<td><input type="submit" value="Submit" class="btn btn-default" /></td>
</tr>
</table>
}
3) Make sure that action method decorated with HttpPostAttribute has list of viewmodel class as parameter.
[HttpPost]
public ActionResult Create(List<ViewModelName> model)
{
try
{
// example to select all amount values
var x = model.Select(x => x.Amount).ToList();
// do something
return RedirectToAction("Index");
}
catch
{
// error handling
return View(model);
}
}
From this point, your model binding should working fine.
Related issue: Need to pass a List<model> to the Http Post in a Controller

How to call multiple partials in parent view in MVC4?

I am trying to call multiple partials in parent view. I have tried multiple way but could not succeed. I think there is something missing in View. Please guide me where i am going wrong.
Note: I have partials in the question. Please suggest me.
The following error:
System.InvalidOperationException: 'The model item passed into the
dictionary is of type 'Aplication.Models.ABC.ClsA', but this
dictionary requires a model item of type
'System.Collections.Generic.IEnumerable`1[Aplication.Models.ABC.first]'.'
Model
public class ClsA
{
public List<first> firsts{ get; set; }
public List<second> seconds{ get; set; }
}
public class first
{
public string Name { get; set; }
public string Address { get; set; }
}
public class second
{
public string Details{ get; set; }
public string Age{ get; set; }
}
Controller
public ActionResult ABC()
{
SDetails sDetails=new SDetails();
var model = new ClsA();
model.firsts = sDetails.Rst();
model.seconds = sDetails.Rs();
return View(model);
}
View
#model Aplication.Models.ABC.ClsA
#Html.Partial("_PartialA");
#Html.Partial("_PartialB.cshtml")
_PartialA
#model IEnumerable<Aplication.Models.ABC.first>
<table>
<tr>
<th>#Html.DisplayNameFor(m => m.Name)</th>
<th>#Html.DisplayNameFor(m => m.Address)</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
</tr>
}
</table>
_PartialB
#model IEnumerable<Aplication.Models.ABC.second>
<table>
<tr>
<th>#Html.DisplayNameFor(m => m.Details)</th>
<th>#Html.DisplayNameFor(m => m.Age)</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Details)
</td>
<td>
#Html.DisplayFor(modelItem => item.Age)
</td>
</tr>
}
</table>
#Html.Partial() Takes a second parameter model. If you do not pass the parameter to #Html.Partial() it will automatically pass the model of the current view.
Parameters
htmlHelper
Type: System.Web.Mvc.HtmlHelper
The HTML helper instance that this method extends.
partialViewName
Type: System.String
The name of the partial view to render.
model
Type: System.Object
The model for the partial view.
You need to update your code from
#Html.Partial("_PartialA");
#Html.Partial("_PartialB");
To
#Html.Partial("_PartialA", Model.firsts);
#Html.Partial("_PartialB", Model.seconds)
You do not need to pass the file extension to the #Html.Partial method
This is an example of loading partial view. The controller has an action to load the data in a partial view.
public ActionResult List()
{
var movies = db.Movies;
return PartialView("_list", movies.ToList());
}
In the partial _list view, you can have something like -
#model IEnumerable<WebApplication1.Models.Movie>
<div class="row">
<table class="table table-bordered table-hover" id="moviesTable">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.ID)
</th>
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th>
#Html.DisplayNameFor(model => model.ReleaseDate)
</th>
<th>
#Html.DisplayNameFor(model => model.Genre)
</th>
<th>
#Html.DisplayNameFor(model => model.Price)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
<div class="btn-group btn-group-xs">
<i class="fa fa-trash-o"></i>
<i class="glyphicon glyphicon-pencil"></i> Edit
<i class="glyphicon glyphicon-eye-open"></i> View
<i class="glyphicon glyphicon-trash"></i> Delete
</div>
</td>
</tr>
}
</tbody>
</table>
</div>
Now you can render the partial view in the main view like below -
<div class="row">
<div class="col-md-12" id="replacetarget">
#{ Html.RenderAction("List", "Movies"); }
</div>
</div>

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 :)

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.

how to get data using #Ajax.ActionLink() in 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);
}

Resources