Delete a row with ajax in mvc3 - ajax

I am trying to do a delete with Ajax from a list view and when I press button "Delete (Ajax)" it doesn't enter on the controller method, it generates the error:
The resource cannot be found. Description: HTTP 404. The resource you
are looking for (or one of its dependencies) could have been removed,
had its name changed, or is temporarily unavailable. Please review
the following URL and make sure that it is spelled correctly.
Requested URL: /Idea/DeleteAjax/30
Any ideas?
//controller
[HttpPost]
public ActionResult DeleteAjax(int id)
{
IdeeRepository ideeRepo = new IdeeRepository();
WIKIIDEE idee = new WIKIIDEE();
idee = ideeRepo.GetIdeeByID(id);
ViewModels.AjaxResponseVM ajaxVM;
try
{
ideeRepo.DeleteIdea(idee);
ideeRepo.SaveIdea();
ajaxVM = new ViewModels.AjaxResponseVM(Convert.ToInt32(idee.ID), "Idee eliminato con successo!");
}
catch
{
ajaxVM = new ViewModels.AjaxResponseVM(-1, "Error!");
}
return Json(ajaxVM);
}
// view
#Ajax.ActionLink("Elimina Idea(Ajax)", "DeleteAjax", "Idea", new { id = ViewBag.Ideas[i].ID }, new AjaxOptions { Confirm = "Are you sure!", OnSuccess = "DeleteResponse", HttpMethod = "POST" })

Make sure you are referencing the following files:
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

Related

performing ajax action from default function throws 'cannot perform runtime binding on a null reference'

I am receiving a 'cannot perform runtime binding on a null reference' error when executing an ajax call from the default action on a controller.
My route definition is as follows:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I have an MVC 5 memecontroller with the following get functions:
public async Task<ActionResult> Index()
{
return View();
}
public async Task<ActionResult> getmeme(string parameter)
{
if (parameter.Equals("improvise"))
{
var absolutelyBarbaric = new string[]{ "adapt ", "improvise ", "overcome"};
if (Request.IsAjaxRequest())
{
return Json(absolutelyBarbaric, JsonRequestBehavior.AllowGet);
}
}
throw new NotImplementedException("to lazy for other examples");
}
the html page adapt.htmlcs is as follows:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function () {
var options = {
url: 'getmeme?parameter=improvise'
};
$.ajax(options).done(function (data) {
var $target = $('#memes');
$target.replaceWith(data);
});
});
</script>
</head>
<body>
<div id="memes">
</div>
</body>
</html>
when I navigate to http://localhost:1234/meme/index, the page loads as normal, with the ajax function calling normally. When i navigate to http://localhost:1234/meme i can see that the index function is called in the debugger, but the ajax call throws an 'cannot perform runtime binding on a null reference' error. Why is this happening, and more importantly, how can i prevent it?
EDIT:
removed use of the ViewBag, since it had no function here

Ajax.ActionLink does not work when OnBegin is true

I intend to call function when clicked on ActionLink and depending on the ouptput of the function would either go the next page or show alert.
When OnBegin is true in Ajax.ActionLink, it should hit the controller method and hence go to specified view. But when I click on the ActionLink, OnBegin returns true but nothing happens. I see the same page.
<script src="~/Scripts/jquery-2.1.0.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
#using (#Html.BeginForm())
{
#Ajax.ActionLink("Add Document", // <-- Text to display
"AddDocument", // <-- Action Method Name
"Home", // <-- Controller Name
null,
new AjaxOptions { OnBegin = "OnBegin('AddDocument')" },
null
)
}
<script type="text/javascript">
function OnBegin(vObject) {
debugger;
return true;
}
</script>
Any help would be appreciated.
Thanks.
I think that you are using it in the wrong way. #Ajax.ActionLink will hit your controller and retrieve the content of the response but you haven't set any space to hold the response. One of the properties of AjaxOptions is UpdateTargetId which should be setted to the id tag that will hold the response.
#Ajax.ActionLink("Add Document", "AddDocument", "Home",
new AjaxOptions
{
OnBegin = "OnBegin('AddDocument')",
UpdateTargetId = "responseContent"
})
In the view put a tag to hold the response:
<div id="responseContent"></div>
The response will be inserted inside the div.

Trying to load a partial view with Ajax.ActionLink

After reading a few other posts on here I've got this far with attempting to load a partial view on the click of a link (the text link may actually change to be an image once I get past this proof of concept stage). The problem is I am being directed to the partial view on click instead of it populating a div within the view I am clicking the link on:
The layout:
<script src="#Url.Content("~/scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
The View:
#Ajax.ActionLink("Item 1 Ajax", "Details", "Portfolio", new { name = "test" }, new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "row1Content",
OnComplete = "portfolioItemLoaded"
})
<div id="row1content"></div>
<script type="text/javascript">
function portfolioItemLoaded() {
alert("Done");
}
</script>
The controller:
public class PortfolioController : Controller
{
public ActionResult Details(string name)
{
return PartialView(name);
}
}
The partial (obviously named test.cshtml):
<p>Item 1 test</p>
Have I missed something obvious? It's the first time I have attempted to use AJAX in MVC, so there might be a school boy error or two.
I am planning on having several different Ajax Action Links that call different partial views, hence the reason I am passing the name in to the controller.
Code fixed
Do you wanna try this, you have a better control, if error, etc....
HTML with helper
#Html.ActionLink("Item 1 Ajax", "Details", "Portfolio", Nothing, New With {.Id = "myLink"})
JavaScript
<script type="text/javascript">
$(document).ready(function() {
$('#myLink').click(getIt);
});
function getIt() {
$.ajax({
type: "POST",
url: $(this).attr('href'),
error: function () {
//show error handler
},
success: function (r) {
$('#row1content').html(r);
}
});
return false;
}
</script>

mvc partial view ajax update returning the partial view as a page

I have a partial view that upon adding an item to the database needs to update.
The Index.cshtml:
#using (Ajax.BeginForm("Index", "WinEntry", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "wingrid", InsertionMode = InsertionMode.Replace}))
{
#Html.Partial("_winVenue")
#Html.Partial("_singleWin")
}
<div id="wingrid">
#Html.Partial("_wingrid")
</div>
The _singleWin has the submit button
The controller:
[HttpPost]
public ActionResult Index(Win win)
{
win.dealerId = "1234567890";
win.posterid = "chris";
win.posttime = DateTime.Now;
wem.addWin(win);
IEnumerable<Win> w = wem.getVenueWins(win.venue,win.windate);
return PartialView("_wingrid",w);
}
When the controller returns the partial view _wingrid it returns it as a new page and the behavior I am looking for is like an update panel inside the wingrid div.
Any help would be appreciated.
You already seem to be doing this thanks to the UpdateTargetId = "wingrid" option in your AJAX form. Just make sure that you clear values that you modify in your POST controller action form the modelstate. Otherwise HTML helpers could still use the old values:
[HttpPost]
public ActionResult Index(Win win)
{
ModelState.Remove("dealerId");
win.dealerId = "1234567890";
ModelState.Remove("posterid");
win.posterid = "chris";
ModelState.Remove("posttime");
win.posttime = DateTime.Now;
wem.addWin(win);
IEnumerable<Win> w = wem.getVenueWins(win.venue,win.windate);
return PartialView("_wingrid",w);
}
Also don't forget to include the jquery.unobtrusive-ajax.js script to your page if you want your Ajax.* helpers to work:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

"UpdatePanel" in Razor (mvc 3)

Is there something like UpdatePanel (in ASPX) for Razor?
I want to refresh data (e.g. table, chart, ...) automaticly every 30 seconds.
Similar to clicking the following link every 30 seconds:
#Ajax.ActionLink("Refresh", "RefreshItems", new AjaxOptions() {
UpdateTargetId = "ItemList",
HttpMethod = "Post"})
Edit:
I may should add that the action link renders a partial view.
Code in cshtml:
<div id="ItemList">
#Html.Partial("_ItemList", Model)
</div>
Code in Controller:
[HttpPost]
public ActionResult RefreshItems() {
try {
// Fill List/Model
...
// Return Partial
return PartialView("_ItemList", model);
}
catch (Exception ex) {
return RedirectToAction("Index");
}
}
It would be create if the PartielView could refresh itself.
You can try something similar to the following using Jquery (have not tested though)
<script type="text/javascript">
$(document).ready(function() {
setInterval(function()
{
// not sure what the controller name is
$.post('<%= Url.Action("Refresh", "RefreshItems") %>', function(data) {
// Update the ItemList html element
$('#ItemList').html(data);
});
}
, 30000);
});
</script>
The above code should be placed in the containing page i.e. not the partial view page. Bear in mind that the a partial view is not a complete html page.
My initial guess is that this script can be placed in the partial and modified as follows. Make sure that the ajax data type is set to html.
<script type="text/javascript">
setInterval(function()
{
// not sure what the controller name is
$.post('<%= Url.Action("Refresh", "RefreshItems") %>', function(data) {
// Update the ItemList html element
$('#ItemList').html(data);
});
}
, 30000);
</script>
Another alternative is to store the javascript in a separate js file and use the Jquery getScript function in ajax success callback.
Well, if you don't need the AJAX expierience than use the HTML tag:
<meta http-equiv=”refresh” content=”30; URL=http://www.programmingfacts.com”>
go here: http://www.programmingfacts.com/auto-refresh-page-after-few-seconds-using-javascript/
If someone wants the complete code for a selfupdating partial view have a look!
Code of the Controller:
[HttpPost]
public ActionResult RefreshSelfUpdatingPartial() {
// Setting the Models Content
// ...
return PartialView("_SelfUpdatingPartial", model);
}
Code of the Partial (_SelfUpdatingPartial.cshtml):
#model YourModelClass
<script type="text/javascript">
setInterval(function () {
$.post('#Url.Action("RefreshSelfUpdatingPartial")', function (data) {
$('#SelfUpdatingPartialDiv').html(data);
}
);
}, 20000);
</script>
// Div
<div id="SelfUpdatingPartialDiv">
// Link to Refresh per Click
<p>
#Ajax.ActionLink("Aktualisieren", "RefreshFlatschels", new AjaxOptions() {
UpdateTargetId = "FlatschelList",
HttpMethod = "Post", InsertionMode = InsertionMode.Replace
})
</p>
// Your Code
// ...
</div>
Code to integrate the Partial in the "Main"-View (ViewWithSelfupdatingPartial.cs):
#Html.Partial("_FlatschelOverview", Model)
The <meta refresh ..> tag in HTML will work for you. Its the best option
Traditional controls don't works in ASP MVC
You could do it using Jquery timers http://plugins.jquery.com/project/timers
Other option could be to use the Delay function
In your target is as simple as refresh the whole page, this SO link will be of your interest: Auto refresh in ASP.NET MVC
Hope It Helps.

Resources