ASP.Net MVC 3.0 Ajax.ActionLink Onbegin Function true the execute the action? - asp.net-mvc-3

I have a Ajax Action link, which will call a action Method,
In my Ajax Option i have called a Validate function,
If this function returns true,
then only i would want this Action Execute, not sure how i can get this done?
My Ajax ActionLink
Ajax.ActionLink("Renew", "Edit", "Controller", new { id = "<#= ID #>" },
new AjaxOptions
{
OnBegin = "isValidDate",
OnSuccess = "DestroyRecreateAccordion",
UpdateTargetId = "accordion",
InsertionMode = InsertionMode.InsertAfter,
}, new { #class = "standard button" })
How can I do this only if isValidDate returns true?

AjaxOptions on Action Link
OnBegin="isValidDate"
JavaScript
function isValidDate() {
var date = $('#dateid').val()'
//...check date....
if(date is valid) return true;
else return false;
}
this worked

You need to return false on your OnBegin Method
OnBegin = "function(){ return isValidDate(); }",
function isValidDate() {
var date = $('#dateid').val()'
...check date....
if(date is valid) return true;
else return false;
}

Related

ActionLink to submit Model value

I want my Ajax.ActionLink to pass a viewModel property to action.
Here is my ViewModel
public class ViewModel
{
public string Searchtext { get; set; }
}
My .cshtml
#Ajax.ActionLink("Bottom3", "Bottom3",new { name = Model.Searchtext}, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "pointsDiv"
})
using(Html.BeginForm("Bottom3", "Home", FormMethod.Get))
{
#Html.TextBoxFor(x => x.Searchtext)
<button type="submit">Search</button>
}
<div id="pointsDiv"></div>
}
My Controller action:
public PartialViewResult Bottom3(string name)
{
var model = db.XLBDataPoints.OrderBy(x => x.DataPointID).Take(3).ToList();
return PartialView("Partial1", model);
}
But the name parameter passed to the action is always null. How do I solve this?
In your code... you have 2 different ways of posting to the server: the link and the form button.
The problem is that the ActionLink has no way to get the value from the input in client side... just the original value.
If you press the Search button, you will see a value posted.
Now, you can use some jQuery to modify a standard ActionLink (not the Ajax.ActionLink):
https://stackoverflow.com/a/1148468/7720
Or... you can transform your Form in order to do a Ajax post instead of a normal one:
https://stackoverflow.com/a/9051612/7720
I did this for a model of mine like so. I ONLY supported the HttpPost method. So add the HttpMethod="POST" to your Ajax.ActionLink
[HttpPost]
public ActionResult Accounts(ParametricAccountsModel model)
{
if (model.Accounts == null)
{
GetAccountsForModel(model);
}
if (model.AccountIds == null)
{
model.AccountIds = new List<int>();
}
return View(model);
}
On the razor view
#Ajax.ActionLink(
"Add Account to Order", "Accounts", "Parametric", null,
new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "...", HttpMethod = "POST" },
new { #id = "AddParametricAccountLink" })
The model has a list of selected account ids. So in javascript, I modified the href of the action link dynamically.
function UpdateParametricAccountAction() {
var originalLink = '/TradeNCashMgmt/Parametric/Accounts';
var append = '';
var numberOfRows = $('#ParametricAccounts').find('.parametric-account- row').size();
for (var i = 0; i < numberOfRows; i++) {
if (i != 0) {
append += '&';
}
else {
append = '?';
}
var idValue = $('#NotionalTransactionsAccountId_' + i).val();
append += 'AccountIds%5B' + i + '%5D=' + idValue;
}
$('#AddParametricAccountLink').attr('href', originalLink + append);
}
Since the model binder looks for parameter names in the query string and form submission, it will pick up values using the href. So I posted a model object using the querystring on my Ajax.ActionLink. Not the cleanest method, but it works.

Get a reference to the anchor element of an Ajax.ActionLink at the OnSuccess handler

Basically my question is similar or even a duplicate of this one, except that I'm using MVC Razor. And I'm certain that the answers there are outdated since the client library currently used is jQuery / unobtrusive ajax.
So to sum up the question, I'm trying to access the anchor element that triggered the Ajax request in the handler specified at the OnSuccess property of the provided AjaxOptions.
Here is the ActionLink:
#Ajax.ActionLink("Add opening times entry", "AddOpeningTimes",
new { htmlPrefix = Html.HtmlPrefixFor(m => Model.OpeningTimes) },
new AjaxOptions { UpdateTargetId = "openingTimes",
InsertionMode = nsertionMode.InsertAfter,
OnSuccess = "updateHtmlPrefix" },
new { title = "Add opening times entry" })
JS:
function updateHtmlPrefix() {
this.href = this.href.replace(/\d(?=]$)/, function (i) { return ++i; });
}
here is a link to an answer that shows several solutions and a good mark explanation of the issue.
https://stackoverflow.com/a/1068946/1563373
you could always just write
OnBegin="function() { clickedLink = $(this); }"
You can then access the clickedLink variable in the success handler (remember to declare it with page scope).
EDIT:
After some playing around with the call stack, you could try something like this:
<script type="text/javascript">
function start(xhr) {
var stack = start.caller;
// walk the stack
do {
stack = stack.caller;
} while (stack.arguments != undefined && stack.arguments.length > 0 && (stack.arguments[0].tagName == undefined || stack.arguments[0].tagName != "A"))
//stack now points to the entry point into unobtrusive.ajax
if (stack.arguments != undefined)
xhr.originalElement = $(stack.arguments[0]);
//blech
}
function UpdateHrefText(result, status, xhr) {
debugger;
if(xhr.originalElement != undefined)
xhr.originalElement.text(result.Message);
}
</script>
#Ajax.ActionLink("Test", "Message", "Home", new AjaxOptions{ OnBegin = "start", OnSuccess = "UpdateHrefText"})
Not sure I would trust this in production though. I'd do something more like:
<script type="text/javascript">
var theLink;
function start(xhr) {
xhr.originalElement = theLink;
}
function UpdateHrefText(result, status, xhr) {
debugger;
if(xhr.originalElement != undefined)
xhr.originalElement.text(result.Message);
}
</script>
#Ajax.ActionLink("Test", "Message", "Home", null, new AjaxOptions{ OnBegin = "start", OnSuccess = "UpdateHrefText"}, new { onclick="theLink = $(this);"})

How can I get the data from my controller into my View via Ajax while returning a View?

I have this action in my controller which is returning a View...
public ActionResult SaveTimeShift(...)
{
try
{
if (Request.IsAjaxRequest())
return PartialView(....);
return View(userRecord);
}
catch (Exception e)
{
return PartialView(...);
}
}
Then this the html code in my viewpage...
using (Ajax.BeginForm("SaveTimeShift", new { }, new AjaxOptions { HttpMethod = "Get", UpdateTargetId = "recordList", InsertionMode = InsertionMode.Replace, Confirm = "Do you want to save the new time shift?", OnSuccess = "partialRequestSuccess(data)", OnFailure = "partialRequestFailure" }, new { #class = "form-inline" }))
{
Now on my partialRequestSuccess(data) function on my OnSuccess parameter of AjaxOptions...
function partialRequestSuccess(data) {
if (data == 1)
alert("New Time Shift has been saved.");
}
Now my problem here is .... Im trying to set a value of my "data" variable that will be set in my controller... I did some research about returning a Json object unfortunately I'm returning a View in my controller... For now my "data" variable has a garbage value...Is there a way of knowing from my client side if my saving of data in the database was a success or not... Thanks! :)
You could store the data in your model or ViewBag in the action method:
ViewBag.MyVariable = "myValue";
then use in in the JavaScript
var myVariable = #Html.Raw(Json.Encode(ViewBag.MyVariable))

ASP.NET MVC - Current Selected value doesnt get selected in IE

In my Action for Editing an item in my model I have:
ViewBag.PossibleSource = context.Source.ToList();
In my View I have:
#Html.DropDownListFor(model => model.SourceID, ((IEnumerable<btn_intranet.Areas.DayBook.Models.DayBookSource>)ViewBag.PossibleSource).Select(option => new SelectListItem
{
Text = (option == null ? "None" : option.SourceName),
Value = option.SourceID.ToString(),
Selected = (Model != null) && (option.SourceID == Model.SourceID)
}))
In Chrome this works as expected. When I pass a model to my view, the current value that's set in my model is the selected value in the list. But in IE8 and 9 it's selected value is the ORIGINAL value my model was set as even though the update does work. So if I selected "hello" originally and then edited to "world". In chrome when i reload the page it will be set to "world" but in IE "hello" is selected in the dropdown even tho "world" is set in my database for my model. It is worth noting these are updated via AJAX
EDIT:
Ajax.Actionlink:
#Ajax.ActionLink(item.ItemNumber, "EditItem", new { id = item.QuoteLineID, enquiryId = item.EnquiryID }, new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "EditItem"
})
This loads the form onto the view.
Ajax.BeginForm:
#using (Ajax.BeginForm("EditItem", new { controller = "QuoteLines" }, new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "Summary"
}, new { #class = "manual-search cf" }))
{
...Other Model inputs
#Html.DropDownListFor(model => model.SourceID, ((IEnumerable<btn_intranet.Areas.DayBook.Models.DayBookSource>)ViewBag.PossibleSource).Select(option => new SelectListItem
{
Text = (option == null ? "None" : option.SourceName),
Value = option.SourceID.ToString(),
Selected = (Model != null) && (option.SourceID == Model.SourceID)
}))
<input type="submit" class="update-items" value="Update Line" />
}
EditItem Action GET request:
public virtual ActionResult EditItem(int id)
{
try
{
DayBookQuoteLines q = context.QuoteLines.Single(x => x.QuoteLineID == id);
ViewBag.PossibleSource = context.Source.ToList();
if (Request.IsAjaxRequest())
{
return PartialView("_EditItem", q);
}
else
{
return RedirectToAction("SalesDetails", new { controller = "Enquiries", id = q.EnquiryID });
}
}
catch (Exception ex)
{
return PartialView("_Error", ex.Message);
}
}
EditItem Action POST request:
[HttpPost]
public virtual ActionResult EditItem(DayBookQuoteLines q)
{
try
{
ViewBag.PossibleSource = context.Source.ToList();
if (ModelState.IsValid)
{
context.Entry(q).State = EntityState.Modified;
context.SaveChanges();
return PartialView("_GetSummary", context.Vehicles.Where(x => x.EnquiryID == q.EnquiryID).ToList());
}
return PartialView("_EditItem", q);
}
catch (Exception ex)
{
return PartialView("_Error", ex.Message);
}
}
I've fixed it, I renamed my GET request for EditItem to EditItemGet and then in my #Ajax.ActionLink I did:
#Ajax.ActionLink(item.ItemNumber, "EditItemGet", new { id = item.QuoteLineID, enquiryId = item.EnquiryID }, new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "EditItem",
HttpMethod = "POST"
})
It was a Cache issue. Thats why it only failed in IE which likes Cache. I read before that making the request a POST request prevents Caching.

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>

Resources