what is the alternative of using url.action in ajax - ajax

E.g.
#url.Action("Actionname", "ControllerName", new { id=#item.id, #class="test"})
I want such a thing in Ajax, like this:
#Ajax.action("Actionname", "ControllerName",new { id=#item.id, #class="test"})
I tried this, but it did not benefit me:
#Ajax.ActionLink(".", "DeleteCountry", "Main", new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "Details" }, new { CountryID = item.CountryID , #class="fa fa-times"}) #Ajax.ActionLink(".", "EditCountry", "Main", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "Details" }, new {CountryID=item.CountryID,#class="fa fa-pencil"})
Can anyone assist me with this?

In asp.net mvc I use both Ajax.BeginForm
#Ajax.BeginForm("Action", "Controller", new AjaxOptions { HttpMethod = "POST", OnSuccess = "successFunction", ... })
{
#Html.HiddenFor(item => item.id)
//etc fields you want to send
}
and JQuery ajax
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: "GET",
data: { 'id': '#item.id' },
success: ...
});
Think it will help you.

Related

MVC 5 AJax.Beginform Routevalues are generated wrongly

I am trying to post to action the current querystring. So i have created the below extension method :
public static RouteValueDictionary ToRouteValues(this NameValueCollection col, Object obj = null)
{
var values = obj != null ? new RouteValueDictionary(obj) : new RouteValueDictionary();
if (col == null) return values;
foreach (string key in col)
{
//values passed in object are already in collection
if (!values.ContainsKey(key)) values[key] = col[key];
}
return values;
}
And in my view i am using the routvalues as below:
using (Ajax.BeginForm(actionName: "Post", routeValues:Request.QueryString.ToRouteValues(), controllerName: "Request", ajaxOptions: new AjaxOptions { HttpMethod = "Post", OnSuccess = "SuccessCallBack", UpdateTargetId = "successDiv", InsertionMode = InsertionMode.InsertAfter }, htmlAttributes: new { #data_toggle = "validator" }))
{
}
But strangely when the html markup is generated the form tag action does not have the actual querystring values but instead has a string version of the object metadata.
<form action="/Request/Post?Count=5&Keys=System.Collections.Generic.Dictionary%602%2BKeyCollection%5BSystem.String%2CSystem.Object%5D&Values=System.Collections.Generic.Dictionary%602%2BValueCollection%5BSystem.String%2CSystem.Object%5D" data-ajax="true" data-ajax-method="Post" data-ajax-mode="after" data-ajax-success="SuccessCallBack" data-ajax-update="#successDiv" data-toggle="validator" id="form0" method="post" novalidate="true">
This works for me:
#using (Ajax.BeginForm(
actionName: "AddOns",
controllerName: "Basket",
routeValues: Request.QueryString.ToRouteValues(),
ajaxOptions: new AjaxOptions { HttpMethod = "Post", OnSuccess = "SuccessCallBack", UpdateTargetId = "successDiv", InsertionMode = InsertionMode.InsertAfter },
htmlAttributes: new Dictionary<string, object> { { "class", "mainForm" } }))
{
#:Blah
}
It outputs:
<form action="/Basket/AddOns?test=test" class="mainForm" data-ajax="true" data-ajax-method="Post" data-ajax-mode="after" data-ajax-success="SuccessCallBack" data-ajax-update="#successDiv" id="form0" method="post">
Blah
</form>
Please note the last parameter which is a Dictionary<string, object>.
Used this post as source: MVC3 Html.BeginForm - passing arguments as RouteValueDictionary fails
The issue is that your using named parameters and there are overloads of Ajax.BeginForm() that accept both object routeValues and RouteValueDictionary routeValues.
In your case its using object routeValues and your generating a route value for each property of RouteValueDictionary (Count, Keys, etc). I'm assuming that's because the overload with object routeValues is defined first (but have yet to find anything documenting the behavior)
You can solve this by omitting the names and using
#using (Ajax.BeginForm("Post", "Request", Request.QueryString.ToRouteValues(), new AjaxOptions { HttpMethod = "Post", OnSuccess = "SuccessCallBack", UpdateTargetId = "successDiv", InsertionMode = InsertionMode.InsertAfter }, new { #data_toggle = "validator" }))
{
}

PagedList.MVC with EnableUnobtrusiveAjaxReplacing and other render option

I've got pager like this:
#Html.PagedListPager(Model.komentarzeListModeracja, page =>
Url.Action("ModeracjaKomentarze", new {
DotyczyID = Model.DotyczyID, page
}),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions() {
HttpMethod = "Get", UpdateTargetId = "ModeracjaUpdate1"
}))
Could You tell me how can I add other render option to this ?. Is it possible ?.
There are already several versions\flavors incorporated into the class (intellisense enabled: Classic to OnlyShowFivePagesAtATime, Minimal and Bootstrap, etc.).
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(PagedListRenderOptions.TwitterBootstrapPagerAligned, new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "divpagedlist" }))
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(PagedListRenderOptions.ClassicPlusFirstAndLast, new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "divpagedlist" }))
Simply, comma separated properties for the class.
A good reference at this time for PagedListRenderOptions (Class) properties:
http://www.nudoq.org/#!/Packages/PagedList.Mvc/PagedList.Mvc/PagedListRenderOptions
(please note this site is beta, cannot be sure how long link will be valid)
Another way...
#Html.PagedListPager(Model, page => Url.Action("FileIndex",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new PagedListRenderOptions()
{
DisplayLinkToLastPage = PagedListDisplayMode.IfNeeded,
DisplayLinkToFirstPage = PagedListDisplayMode.IfNeeded,
Display = PagedListDisplayMode.IfNeeded,
LiElementClasses = new List<string> { "myClass", "yourClass" },
MaximumPageNumbersToDisplay = 10
}, new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "fileListTable" }))

Change ajax UpdatetargetID depends of model state validation MVC

Lets say i've got simple ajax begin form:
#using (Ajax.BeginForm("DodajTresc", "Administracja", new AjaxOptions { Confirm = "Czy jesteś pewien że chcesz dodać treść ?", InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace, UpdateTargetId = "podgladDodanejTresc", LoadingElementId = "spinWiadomosci" }))
{
some code[...]
}
Is it possible to change UpdatetargetID after post depends of model state validation ?. For exmaple:
if(ModelState.IsValid)
{
UpdatetargetID="div1";
}
else
{
UpdatetargetID="div2";
}
Is there an option to achieved that ?

Passing routeValues to Controller in MVC 3

i have this code in View
#using (Html.BeginForm())
{
#: Location #Html.DropDownList("territryID", (SelectList)ViewBag.Territory, "choose one")
#Ajax.ActionLink(
"ok",
"Info", new { territryID = "#territryID" },
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "post1"
})
<div id="post1">
</div>
}
and this code in my Controller
[HttpPost]
public ActionResult Info(int? territryID)
{
if (territryID == null)
{
return RedirectToAction("Info");
}
var model = (from c in _db.OCRDs
where c.Territory == territryID
select c).Distinct();
return PartialView("_getCustomerByTerritory", model);
}
how to passing my dropdownlist selected value to territryID parameter in controller, how to do that?
thanks,
erick
How about this, initialize your URL to something like this (also note the assignment of an id to the link):
#Ajax.ActionLink("ok", "Info", new { territryID = "REPLACEME" }, new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "POST", UpdateTargetId = "post1" }, new { id = "oklink" })
Replace the placeholder (REPLACEME) when the dropdown changes, like so:
<script>
$('#territryID').change(function () {
var newid = $('#territryID').val();
var oldLink = $('#oklink').attr('href');
var newLink = oldLink.replace('REPLACEME', newid);
$('#oklink').attr('href', newLink);
});
</script>

MVC3 Ajax.ActionLink

For the following:
#Ajax.ActionLink("Delete", "Delete", "AdminGroup", new { id = item.AdminGroupId }, new AjaxOptions { Confirm = "Delete?", HttpMethod = "Delete", OnSuccess = "function() { $(this).parent().parent().remove() }" })
OnSuccess get's errored out. please help.
thanks
It should be like this:
#Ajax.ActionLink(
"Delete",
"Delete",
"AdminGroup",
new { id = item.AdminGroupId },
new AjaxOptions {
Confirm = "Delete?",
HttpMethod = "Delete",
OnSuccess = "handleSuccess"
}
)
where you have:
<script type="text/javascript">
function handleSuccess() {
// TODO: handle the success
// be careful because $(this) won't be
// what you think it is in this callback.
}
</script>
Here's an alternative solution I would recommend you:
#Html.ActionLink(
"Delete",
"Delete",
"AdminGroup",
new { id = item.AdminGroupId },
new { id = "delete" }
)
and then in a separate javascript file AJAXify the link:
$(function() {
$('#delete').click(function() {
if (confirm('Delete?')) {
var $link = $(this);
$.ajax({
url: this.href,
type: 'DELETE',
success: function(result) {
$link.parent().parent().remove();
}
});
}
return false;
});
});

Resources