Passing variable to Ajax.ActionLink OnSuccess, OnComplete, OnFailure, etc - asp.net-mvc

I'd like to put a div on my master page that I can update from anywhere in my site with updates. i.e. "recorded updated", "there was an error", etc.
I'm going to style the div differently depending on the type of update. "fail", "success", "info". Basic stuff so far.
So I have several ActionLinks throughout the site and they display their content fine in the updateTarget and I can even have them run fine when I pass OnComplete, OnBegin, etc. functions to them. However, I'd like to be able to send a parameter to that OnBegin function.
Example:
.OnBegin="someFunction('fail');"
Any ideas on how to accomplish what I'm doing here?

<% string message = "failed"; %>
<%=Ajax.ActionLink("TestController","TestAction",
new AjaxOptions{OnBegin="myFunction('" + message + "')"}) %>

You can create an anonymous function, and next call your function with your paramas
<%: Ajax.ActionLink("Text", "ActionName", new { id = item.id }, new AjaxOptions { HttpMethod = "Post", OnComplete = "function(){myFunction(" + item.id.ToString() + ");}" })%>
The script:
<script type="text/javascript">
function onDelete(id) {
alert("hello "+id);
}
</script>

Related

Removing record from view on a Ajax.ActionLink C# MVC

I have a piece of code that i thought worked at one time. I may have it wrong and cannot find anything like it through my search. The below code deletes the record but does not remove the record from the view without refreshing the page. Can anyone see what might be wrong with this?
#Ajax.ActionLink("Delete", "Delete", new { id = item.VendorId },
new AjaxOptions()
{
HttpMethod="Delete",
Confirm="Are you sure you want to delete this " + item.VendorName,
OnComplete = "function() { $(this).parent().parent().remove }"
}, new { #class = "btn btn-danger btn-sm" })
I am using DataTables if that has anything to do with it.
Thanks for your help!
So what i ended up doing, not sure if it is right or not. I took the line out of OnComplete added Delete to the class and created another function. It works, but not sure if it is overkill or not..
$(document).on('click', '.Delete', function () {
$(this).parent().parent().remove();
});

View rails record details in bootstrap modal on row click

I have been stuck on this problem for quite some time now and looked through several posts as well, however I cannot achieve exactly what I want for my Rails application. Essentially, I want to be able to click on a table row on my page and have a modal pop up which displays all the information for that specific record. Here are the scenarios which I have thought of/attempted partially:
Set the data-link attribute in table row with some JS as follows
HTML:
<tr data-link="<%= kid_path %>">
...
</tr>
JS:
$("tr[data-link]").dblclick(function() {
window.location = $(this).data("link")
})
This worked fine to open the show path page generated by the scaffold, but I was not able to modify it to work with a modal and have the same data for the kid in the modal.
Use data-id and JavaScript to load onto the modal
HTML:
<tr data-id="<%= kid.id %>">
...
</tr>
JS:
$(function () {
$('#showModal').modal({
keyboard: true,
backdrop: "static",
show: false,
}).on('show', function () {
});
$(".table-striped").find('tr[data-id]').on('click', function () {
debugger;
$('#showDetails').html($('<p>' + 'Kid ID: ' + $(this).data('id') + '<%= Kid.find(30).first_name %>' + '</p>'));
$('#showModal').modal('show');
});
});
In this approach I am able to load the modal on row click and am able to access the Kid ID, however I cannot move further to access other attributes of the record. For example, I want to set #Kid = kid.find(id) using JS where id would be the extracted ID from the row. And then, I want to be able to write the generic modal template which displays other elements (ex. kid.first_name, kid.last_name, etc).
I am totally stuck and cannot find any approach that helps to accomplish my goal. Any help is appreciated, thank you.
You need to ajax call record attributes because the line Kid.find(30).first_name doesn't exist at the time page loaded.
Try this:
KidsController
def show
kid = Kid.find(params[:id])
respond_to do |format|
format.html { // Usually show.html.erb }
format.json do
# Return kid as json object
result = {
first_name: kid.first_name,
last_name: kid.last_name
}
# If you want to return the whole kid record attributes in json: result = kid.attributes.to_json
render json: result
end
end
end
Try /kid/[:id].json to verify that you are not getting UnknownFormat error.
JS
$(".table-striped").find('tr[data-id]').on('click', function () {
var kid_id = $(this).data('id');
$.getJSON("/kid/" + kid_id, function(data) {
// Render the modal body here
// first_name = data.first_name, last_name = data.last_name etc
$('#showDetails').html($('<p>'+ data.first_name + '</p>'));
$('#showModal').modal('show');
});
})
If you have setup correct route for Kid model then these are what you needed.
UPDATED: I made a typo in the result hash. FIXED

Is it possible to submit a hidden field and control its value with x-editable?

inside the document of X-editable, we can create a new record, but how to edit an existing record, and post its name and email fields as well as its id =1(this id not changed) to the backend?
<table>
<thead><th>id</th><th>name</th><td>email</th></thead>
<tbody>
<tr><td><span>1</span></td><td><span class='myeditable'>name</span></td><td><span class='myeditable'>email#example.com</span></td></tr>
</tbody>
</table>
$('.myeditable').editable({
type: input,
url: '/edituser'
});
$('#save-btn').click(function() {
$('.myeditable').editable('submit', {
url: '/edituser',
ajaxOptions: {
dataType: 'json' //assuming json response
},
success: function(data, config) {
if(data && data.id) { //record created, response like {"id": 2}
},
error: function(errors) {
}
});
});
I used Angular-xeditable to do this, but the idea is the same I think.
I added a hidden span to my table and gave it an e-name. ng-show sets display:none, which I think is just what you need to do as well.
<span
editable-text="journalEntry._id"
e-name="_id"
e-form="rowform"
ng-show="false">
</span>
I used Angular-xeditable also, but had to change Michael's code because the hidden field appeared (I wanted it to remain hidden) when I edited the row.
Therefore I had to insert
e-class="hidden"
So in the end I had:
<span
e-class="hidden"
editable-text="employee.key"
e-name="key"
e-form="rowform"
ng-show="false">
</span>
To post a hidden field, you could try to modify your
url: '/edituser'
to
url: '/edituser?hidden-name1=hidden-value1&hidden-name2=hidden-value2' and so on...

Auto refresh <div> without reload entire page

I'm trying to update the content of "mydiv" without refreshing the entire index page.
#mydata is given by mycontroller. I need to recalculate it every n seconds and pass it to "mydiv"
With "link_to" it works!
index.html.erb
<%=
link_to('refresh', '/mycontroller/index', :remote => true)
%>
<div id="mydiv">
<%=
#mydata
%>
</div>
index.js.erb
$('#mydiv').html('<%= escape_javascript(#mydata) %>')
Now I need to refresh the content of "mydiv" automatically every n seconds (so without click on the link). I have tried solutions from:
First Link
Second Link
but no luck.
In my application.js I have writed this:
function executeQuery() {
$.ajax({
//url: '/index',
success: function(data) {
$('#mydiv').html(data)
}
});
setTimeout(executeQuery, 500);
}
$(document).ready(function() {
setTimeout(executeQuery, 500);
});
For who is facing my same problem, I solved it by replacing
$('#mydiv').html(data)
with
$('#mydiv').load('/mycontroller/index #mydiv')
Use setInterval() instead of using setTimeout().
Ref: https://www.w3schools.com/jsref/met_win_setinterval.asp
function executeQuery() {
$.ajax({
type: 'GET',
url: 'example.com/url/', // Provide your response URL here.
success: function(data) {
$('#mydiv').html(data);
}
});
}
setInterval(executeQuery(), (n * 1000)); // Replace 'n' with how many seconds you want.
This code will run the executeQuery() method in every 'n' seconds interval. So that your requirement is accomplished.
Set layout to false in the action and just pass on the relevent content, not the entire page
def action1
<your code here>
end
def action2
<your code here>
render :layout => false
end
Your view for action2 should have content pertaining only to #mydiv.
A better solution would be to use a single action and change render options based on type of request. (Ajax or non ajax)

How can I update a page content with jQuery Ajax and ASP.NET MVC?

I have a ActionResult named "MyPeriods(string dateSelected)" and in the end of it, I have a ViewData["periods"] = listOfPeriods (and after that, I have my return View(), fininshing up my method). When no "date" is passed, "date" is today, otherwise, "date" is the date passed as argument. And this "date" is important to select all the periods and events relationed to it.
So, my ActionResult is sending a list of periods to my View. In my View, I have:
<div id="divEventsPeriods">
<% foreach(UserPeriod period in in (IEnumerable)ViewData["periods"])
Response.Write("<div>PERIOD: " + period.hourBeg + " - " + period.hourEnd + "</div>");
foreach(UserEvents event in period.UserPeriod) {
Response.Write("<div>EVENT: " + event.date + "<br />");
Response.Write("DESCRIPTION: " + event.description + "</div>");
}
%>
</div>
So, when I select a date in jQuery DatePicker, this selected date is passed as an argument to my ActionResult and all the process occurs. And, in the end of all, my page refreshes rendering all the Periods and Events of the selected date. One Period may have many Events.
So, the question is: how can I pass this selected date to my ActionResult, making all process occurs and the page becomes updated without refreshing?
I've tried this on DatePicker onSelect option:
$.ajax({
type: 'GET',
url: '/Admin/Schedule/MyPeriods/?dateSelected=' + dateSelected,
data: dateSelected
});
When I select a date, the $.ajax is called and debugging I could see that the selected date is passed correctly to my ActionResult and process occurs, but the page is not updated.
What am I doing wrong??
Thanks in advance!!
You need to add a success callback to the ajax call that will accept the returned data and update your page via DOM manipulation, for example, by replacing the contents of a DIV with the HTML (presumably) returned by your action. I'm assuming here that your action returns a ContentResult. If you are returning a JsonResult instead, then you'll need use the result and do what is necessary to update the DOM.
Take a look at the jQuery AJAX options page for more information.
EDIT I decided to do this in one method, but using IsAjaxRequest(). Your client side code may not need to change at all with the exception of using the partial as noted below.
public ActionResult ViewPage(DateTime dateSelected)
{
....do some stuff...
ViewData["dateSelected"] = GetPeriods( dateSelected );
if (Request.IsAjaxRequest()) {
return PartialView("PeriodDisplay", ViewData["dateSelected"]);
}
else {
return View();
}
// common code to populate enumerable
public IEnumerable<Period> GetPeriods( DateTime selected )
{
return ...data based on date...
}
PeriodDisplay.ascx : this should be a strongly typed ViewUserControl using a model of IEnumerable.
<%# Page ... %> /// page definition...
<% foreach(UserPeriod period in Model) { %>
<div>PERIOD: <%= period.hourBeg + " - " + period.hourend %> </div>
<% foreach(UserEvents event in period.UserPeriod) { %>
<div>
EVENT: <%= event.date %><br/>
DESCRIPTION: <%= event.description %>
</div>
<% } %>
ViewPage.aspx
...
<div id="divEventsPeriods">
<% Html.RenderPartial( "PeriodDisplay", ViewData["periods"], null ); %>
</div>
Your action need to return either html or text or whatever you want to show, or JSON objects that you then process in your javascript. From the jQuery.ajax documentation:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
The msg variable in this case is the html / text that you get back from your action. Your action can return a partial view or something as simple as <p>Date Selected feb 12th 2009</p>. You can also use ("#message").html(msg) to insert html into your webpage.

Resources