I am implementing deletion functionality on web grid.
I have a column which has a link delete when it is clicked a JavaScript function is called which sends the id of that record to controller who calls a remove method to delete that record but when i debug the code list of vehicles are returned but when delete link is clicked
it gives a error A data source must be bound before this operation can be performed.
view:
#model IEnumerable<ParkOnMyDrive.Models.Vehicle>
#{
ViewBag.Title = "ViewVehicle"
}
<h2>ViewVehicle</h2>
#{
var grid = new WebGrid(source: Model,
defaultSort: "make",
rowsPerPage: 3);
}
<h2>Vehicle List</h2>
<div id="grid">
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("vehicleType","Type"),
grid.Column("make", " Make"),
grid.Column("modelType", "Model"),
grid.Column("color", "Color"),
grid.Column("registartion", "Registartion"),
grid.Column(
header: "Action",
format: #<text>
<a href="#" id="Delete_#item.vehicleId" >Delete</a></text>)
)
)
Controller:
[HttpPost]
public ActionResult DeleteVehicle(string vehcKey)
{
//string key = "eb306a32-1be0-47ad-a0e8-756af97643b8";
Vehicle vehicleModel = new Vehicle();
string userName = "wasfa_anjum#yahoo.com";
if (ModelState.IsValid)
{
bool success = vehicleModel.RemoveVehicle(vehcKey,userName);
if (success)
{
ModelState.AddModelError("", "Vehicle deleted successfully");
}
else
{
ModelState.AddModelError("", "Vehicle not deleted");
}
}
else
{
}
return View();
}
Model
public bool RemoveVehicle(string vehicleKey,string userName)
{
bool success = false;
using (var session = MvcApplication.Store.OpenSession())
{
var removeVehicle = from vehc in session.Query<Vehicle>()
where vehc.vehicleId == vehicleId
where vehc.userId == userName
select vehc;
if (removeVehicle.Count() > 0)
{
var myVehicle = removeVehicle.FirstOrDefault();
Session.Delete(myVehicle);
Session.SaveChanges();
success = true;
}
}
Related
I have a small problem in my code.. I'm trying to delete a row from database, but without using DataTables (in asp.net mvc) and it doesnt work. I've displayed every item from the database on a page in div's.. It looks like this
Index:
Default Edit/Delete buttons
<input type="button" value="Edit" class="btn btn-warning btn-sm mt-auto" onclick="location.href='#Url.Action("Edit", "Products", new { id = item.Id })'" />
<input type="button" value="Delete" class="btn btn-danger btn-sm mt-auto" onclick="location.href='#Url.Action("Delete", "Products", new { id = item.Id })'" />
with default button I would have to go to the Delete View and press Delete again,and I dont want that.. thats why I'm using Bootbox with Ajax
So I deleted that Delete button and added this:
<button data-product-id="#item.Id" class="btn btn-danger btn-sm mt-auto js-delete">Delete</button>
This is my controller
// GET: Products/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
// POST: Products/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Product product = db.Products.Find(id);
db.Products.Remove(product);
db.SaveChanges();
return RedirectToAction("Index");
}
and this is my script that I'm using
$(document).ready(function () {
$(".products-panel .js-delete").on("click", function () {
var button = $(this);
bootbox.confirm("Do you want to delete this product", function (result) {
if (result) {
$.ajax({
url: "/Products/Delete/" + button.attr("data-product-id"),
method: "GET",
success: function () {
$(button).parent().parent().remove();
},
error: function (err) {
console.log(err);
}
});
}
});
});
});
Currently it only removes the div of that item until you refresh the page.. (it doesnt remove it from the database).. Is there any way that I can fix this
If someone needs more photo's I can provide them..
I fixed the problem, I just had to remove the GET Delete action from the Controller and Change the name on the Post method from DeleteConfirmed to Delete
Previous:
// GET: Products/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
// POST: Products/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Product product = db.Products.Find(id);
db.Products.Remove(product);
db.SaveChanges();
return RedirectToAction("Index");
}
Working:
// POST: Products/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
Product product = db.Products.Find(id);
db.Products.Remove(product);
db.SaveChanges();
return RedirectToAction("Index");
}
Thanks for the people that tried to help
I'm trying to remove or hide items from a list and I'm facing two problems, 1- the newly cannot be removed, 2- Tried to tag the deleted items as isDeleted = true using Javascript then later delete them in the controller following this answer https://stackoverflow.com/a/40572625/10773318 but it didn't work.
Here's my view models
public class CreateEditParentViewModel
{
public int Id { get; set; }
public IList<ChildViewModel> ChildrenLists { get; set; }
}
public class ChildViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool isDeleted { get; set; }
}
In the main view
<div id="editorRows">
#foreach (var item in Model.ChildrenLists)
{
<partial name="_RowPartial" model="item" />
}
</div>
<a id="addItem" asp-action="BlankRow" asp-controller="Home">Add Row...</a> <br />
<input type="submit" value="Finished" />
The javascript in the main view
#section scripts {
<script>
$("#addItem").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#editorRows").append(html); }
});
return false;
});
$("a.deleteRow").click(function () {
$(this).parents("div.editorRow:first").remove(); //does not work with newly added
return false;
}); //what it should do: hide and set isDeleted = true if id is not null - remove if null
</script>
Finally the partial view
<div class="editorRow">
#using (Html.BeginCollectionItem("ChildrenLists"))
{
#Html.HiddenFor(m => m.Id)
#Html.HiddenFor(m => m.isDeleted)
<span>Name: </span> #Html.EditorFor(m => m.Name);
}
delete
1- the newly cannot be removed
You can manually bind click event handler for the new generated <a href="#" class="deleteRow"> element, like below.
success: function (html) {
$("#editorRows").append(html);
$("a.deleteRow").bind("click", function () {
//...
//code logic here
});
}
2- Tried to tag the deleted items as isDeleted = true using Javascript
To achieve the requirement, you can refer to the following code snippet.
<script>
$("#addItem").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) {
$("#editorRows").append(html);
$("a.deleteRow").bind("click", function () {
del_row($(this));
});
}
});
return false;
});
$("a.deleteRow").click(function () {
del_row($(this));
return false;
});
function del_row(el) {
console.log("del");
console.log($(el).siblings("input[id$='__Id']").val());
var childitem_id = $(el).siblings("input[id$='__Id']").val();
if (childitem_id == 0 || childitem_id == "") {
$(el).parent("div.editorRow").remove();
} else {
$(el).siblings("input[id$='__isDeleted']").val("true");
$(el).parent("div.editorRow").hide();
}
return false;
}
</script>
Test Result
I am using an ajax.beginform to create a partial view within another view.
I the user enters a correct sn everything works fine.
But if the user enters an invalid number, I want to redirect to the index view.
Now the index page is submitted as a partial view in itself.
How can I avoid that.
Here is a part of my view and 2 simplified actionresults.
#using (Ajax.BeginForm("MachineInfo", "QrCreate", new AjaxOptions() {
HttpMethod = "POST", UpdateTargetId = "form-content", InsertionMode =
InsertionMode.ReplaceWith }))
{
#Html.AntiForgeryToken()
<input type="text" id="sn" name="sn" class="inputsn"
placeholder="Enter your serial number here..." />
<input type="submit" value="Search" class="search btn btn-success btn-lg" />
}
</div>
</div>
<div id="form-content"></div>
my Controller
public ActionResult Index(bool? isValidMachine = null)
{
ViewBag.invalidSerialNumber = isValidMachine;
return View();
}
[HttpPost]
public ActionResult MachineInfo(string sn)
{
if(string.IsNullOrEmpty(sn))
RedirectToAction("Index", new { isValidMachine = false });
QrCreateViewModel qrCreateVM;
using (var machineService = new MachineApiService())
{
var machine = machineService.GetMachineFromSerialNumber(sn);
if (machine == null)
return RedirectToAction("Index", new { isValidMachine = false });
else
qrCreateVM = new QrCreateViewModel(machine, GetBasePath());
}
if (qrCreateVM.IsValid())
{
qrCreateVM.Viewurl = qrCreateVM.QrCreateUrlOrDefaultNull();
return PartialView(qrCreateVM);
}
else
return RedirectToAction("Index", new { isValidMachine = false });
}
Ajax calls do not redirect (the purpose of making them is to stay on the same page).
In your controller method, replace the instances of return RedirectToAction(...) to return a HttpStatusCodeResult indicating an error, which you can then handle in the OnFailure option to redirect to the Index() method.
For example
[HttpPost]
public ActionResult MachineInfo(string sn)
{
if (string.IsNullOrEmpty(sn))
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Bad Request");
}
....
Then in the Ajax.BeginForm()
#using (Ajax.BeginForm("MachineInfo", "QrCreate", new AjaxOptions() {
HttpMethod = "POST",
UpdateTargetId = "form-content",
InsertionMode = InsertionMode.ReplaceWith,
OnFailure = "redirect"
}))
{
....
and add the following script to redirect
function redirect(ajaxContext) {
location.href = '#Url.Action("Index")';
}
Newbie ALERT
Basically I have a web application that has a dropdown list. When you select an item in the drop-down list the table is drawn to show all the credentials that are tied to that drop-down option.
Problem: When running, everything functions properly except for the JavaScript piece that does not remove the line in the table, but deletes the record on the back-end. So once i refresh and go back to that credential type the one I deleted is gone.
I've tried a lot of different stuff, but i pretty new to JavaScript and C#, don't know if there is a better way of doing this. Probably supplied too much information but i rather too much than not enough! :)
Any help, tips, ideas are greatly appreciated.
Credential API Controller: Delete Function
[HttpDelete]
public IHttpActionResult DeleteCustomer(int id)
{
var credentialInDb = _context.Credentials.SingleOrDefault(c => c.Id == id);
if (credentialInDb == null)
return NotFound();
_context.Credentials.Remove(credentialInDb);
_context.SaveChanges();
return Ok();
}
Model for Credential
public class Credentials
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
[Required]
[StringLength(255)]
public string Username { get; set; }
[Required]
[StringLength(255)]
public string Password { get; set; }
public string Website { get; set; }
public string Notes { get; set; }
public CredentialType CredentialType { get; set; }
[Display(Name = "Credential Type")]
public int CredentialTypeId { get; set; }
}
ViewModel for CredentialFormViewModel
This allows the selectedCredential variable for the page below
public class CredentialFormViewModel
{
public IEnumerable<CredentialType> CredentialTypes { get; set; }
public Credentials Credentials { get; set; }
public int SelectedCredentialTypeId { get; set; }
}
View that displays the DataTable:
#model Appp.ViewModels.CredentialFormViewModel
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Select a Credential Type</h2>
#Html.DropDownListFor(m => m.SelectedCredentialTypeId, new SelectList(Model.CredentialTypes, "Id", "Name"), "Select Credential Type", new { #class = "form-control", onchange = "SelectCredType()" })
<br/>
<table id="credentials" class="table table-bordered table-hover">
<thead>
<tr>
<th>Credential</th>
<th>Username</th>
<th>Password</th>
<th>Website</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
#section scripts
{
<script>
function SelectCredType() {
var credId = $('#SelectedCredentialTypeId').val();
if ($.fn.dataTable.isDataTable("#credentials")) {
if (credId == "") {
var table = $("#credentials").DataTable();
table.destroy();
} else {
var table = $("#credentials").DataTable();
table.destroy();
SelectCredType();
}
} else {
$(document)
.ready(function() {
var table = $("#credentials")
.DataTable({
ajax: {
url: "/api/credentials?credentialTypeId=" + credId,
dataSrc: ""
},
columns: [
{
data: "name",
},
{
data: "username"
},
{
data: "password"
},
{
data: "website"
},
{
data: "id",
render: function(data, type, credentials) {
return "<button class='btn btn-primary btn-xs js-delete' data-credential-id=" + credentials.id + ">Delete</button>";
}
}
]
});
}
);
}
};
$("#credentials")
.on("click",
".js-delete",
function() {
var button = $(this);
bootbox.confirm("Are you sure you want to delete this?",
function(result) {
if (result) {
$.ajax({
url: "/api/Credentials/" + button.attr("data-credential-id"),
method: "DELETE",
sucess: function() {
table.row(button.parents("tr")).remove().draw();
}
});
}
});
});
</script>
}
First issue
Your JavaScript code does not work because the table variable is undefined within your delete function.
There are many ways you could approach to fix that. But first you will need to get your head around variable scopes in JavaScript.
Your simplest solution is to make table a globally-scoped variable that way you can access the instance from any function you create. So instead of defining it here:
...
$(document)
.ready(function() {
var table = $("#credentials")
...
Move it up to the top of your script file:
var table;
function SelectCredType() {
...
$(document)
.ready(function() {
table = $("#credentials")
...
}
Now when you access it from your Delete function, it will be defined.
Note: I would also change the name of the table variable to something else as global variables in JavaScript will conflict with any script you import which can lead to a debugging nightmare. Best to name it something that will be most likely unique, eg. coberlinTable.
Second Issue
I don't know if you did a cut and past error, but you have misspelled success in your ajax Delete function.
Hi I am working with mvc4
I have a razor view page for the action
public ActionResult DeliveryAddress(string userid,int productid)
{
....
return View(m);
}
that contain
<div >DELIVER HERE</div>
when clicking on this i am collecting somedata ifrom this page using jquery,
$(document).ready(function () {
$("#place-order").click(function () {
var userid = $('#selected-userId').html();
var productid = $('#selected-productId').html();
$.get("Products/PlaceOrder/"+ userid, function (data) { });
});
});
and i want to pen another view of action
[HttpGet]
public ActionResult PlaceOrder(int uid)
{
return View();
}
and paste the variable content,
but $.get("Products/PlaceOrder", function (data) { }); is not hitting this action..
please help me.
This is how you need to pass a data to a url in Jquery get method, note the same parameter name is used in the function
$.get('#Url.Action("PlaceOrder","Products")', { uid: userid }, function (data)
{
});
Make sure your URL is correct. Most probably use #Url.Action(). and also pass the parameter using new as shown below.
$.get('#Url.Action("PlaceOrder","Products",new { userid = #userid , productid = #productid })', function (data) {
});
While collecting the data make sure your parameter names are same for both while sending and while receiving.
[HttpGet]
public ActionResult PlaceOrder(int userid, int productid )
{
return View();
}
Just add HTTPGET attribute in your action method as below.
[HttpGet]
public ActionResult PlaceOrder()
{
return View();
}
java script
$("#place-order").click(function () {
var userid = $('#selected-userId').html(); // $('#selected-userId').val();
$.get('#Url.Action("PlaceOrder","Products", new { uid = userid })', function (data) { });
var productid = $('#selected-productId').html();
});
When I want my view code to be fetched like that, or even through the Html.Action() call, I use the PartialView and normally set my Controller Action as:
public ActionResult PlaceOrder(int uid)
{
return PartialView(new TestViewModel() { ID = uid });
}
as an example:
TestViewModel
public class TestViewModel
{
public int ID { get; set; }
}
PlaceOrder.cshtml
#model TestViewModel
<h2>Partial View</h2>
<p>
Partial View paragraph with the id <b>#Model.ID</b>
</p>
Index.html
<hr />
#Html.Action("PartialView", "Home", new { id = 44 })
<hr />
<div class="ap"></div>
<script>
var url = '#Url.Action("PartialView", "Home")';
$.get(url, { id: 54 }, function (data) {
$(".ap").append(data);
});
</script>
result: