ASP.Net MVC how to invoke the action method every 10 seconds - asp.net-mvc

Sorry if this is a silly question.
I have a simple MVC action method which retrieves data from database. I would like to call this action method every 10 seconds to get new data.
Basically need a way to refresh the index page, thereby calling the index method, which gets the latest data from db and display it here.
Can anyone help how to do this in asp.net 4.5 mvc EF code first.
This is a simple mvc application.
Thanks

If you`re sure that it is what you want to do, you can achieve it using jquery:
$(document).ready(function () {
setInterval(function () {
callMyAPI();
}, 10000);
});
function callMyAPI() {
return $.ajax({
url: 'YOUR_URL',
type: "GET",
dataType: "JSON"
});
}

Related

Populating a ViewModel with the current form data before sending it off via JSON

I'm creating an ASP.NET MVC 5 SQL Server (Entity Framework, database-first) application where there is an order record and a set of line item records attached to it. I am using viewmodels to display the data. The user can add new line item records to the viewmodel through an "Add" button, but the line items are not committed to the database until the user clicks the "Save" button. (I've previously written about the application regarding a different issue: ASP.NET MVC - passing modified viewmodel from AJAX to view)
I have the "Add" button working fine... except for one very important use case. If the user changes some data in the web page then presses the "Add" button, none of the changes to the web page data are sent when the #Html.Raw(Json.Encode(Model)) line is called:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#mybutton").click(function () {
$.ajax({
url: "../AddNewLineItem/",
cache: false,
type: "POST",
data: {
'viewModel': #Html.Raw(Json.Encode(Model)),
},
success: function (data) {
$('#divPartial').append(data);
},
error: function (reponse) {
alert("Error: " + reponse);
}
});
});
});
</script>
Obviously, the reason why this is happening is because the model has not been updated with the latest data from the web page. However, how do I force the model to be updated before shipping it off via JSON? (Alternately, is there some way to always keep the viewmodel in sync with what the user has typed in the form?)
the Model object is a server-side entity that doesn't exist on the client. instead, you need to send the client data. try using jQuery's serialize method. this will take all elements in the form and turn it into an object that can be sent via the AJAX method:
data: {
'viewModel': $("form").serialize(),
},

jquery ajax call to ASP.NET MVC controller returns a MediaTypeFormatter exception

Technical Background - We're using :
1) asp.net 4.5 with VS2012
2) Durandal JS for building Single-Page-Apps (SPAs).
3) Breeze JS for querying data.
Now in my jquery ajax call, I'm calling into the Breeze Web API controller as follows:
jsonData.push({
"nodeType": vm.nodeType,
"nodeDescription": vm.nodeDescription,
"NodeDefs": ds.data() // ds dataset is coming from a grid
});
var jsonDataStr = JSON.stringify(jsonData); CONVERT DATA TO JSON
var jq = $.ajax({
url: '/api/breeze/UpdateNode/',
type: "PUT",
dataType: "json",
data:jsonDataStr,
async: false,
});
and my controller looks like this:
[HttpPut]
public SaveResult UpdateNode(JObject saveBundle)
{
SaveResult saved = new SaveResult();
return saved;
}
However I'm getting the following exception return from my jQuery FAILED EVENT :
"ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'JObject' from content with media type 'application/x-www-form-urlencoded'.
So my main question is: how can I make a successful call into my Breeze API controller with the correct JSON data ?
UPDATE AT 1:50pm EST: If I specify type: "STRING" or "JSON" in my jquery ajax call, define my parameter type as STRING in my c# Controller method, the call works fine. However, ideally I want to pass this data object as JSON and my controller should handle it properly.
Thanks in advanced.
Bob
Your controller will need [BreezeController] attribute as mentioned here http://www.breezejs.com/documentation/web-api-controller
I had to change my javascript code to NOT use the javascript array and the subsequenst jsonData.push() and stringify().
Instead I needed a straight jsonData={} object as follows :
var jsonData = JSON.stringify({
"nodeType": vm.nodeType,
"nodeDescription": vm.nodeDescription,
"NodeDefs": ds._data // gives me just the data from Kendo grid data source
});
I was then able to successfully make an ajax call to my controller as follows :
var jq = $.ajax({
url: '/api/breeze/UpdateNode',
type: "post",
dataType: "json",
contentType: 'application/json',
data: jsonData
});
All is good and I'm able to nicely put a break point inside my controller and receive the JObject parameter with issue.
thank you.
Bob

jQuery.Validation.Unobtrusive client side validation only works when scripts are on view page

I have an ASP.NET MVC 4 App that uses the jQuery.validation.js plugin and MVC's jQuery.validation.unobtrusive.js. I use data annotations on my view model to validate a textbox's input to be an integer.
This (nested) view is loaded within a parent view using...
<% Html.RenderPartial("New"); %>
One the first inital page load, client side validation works. But any reloading of the nested view with an ajax call, client side validation no longer works. Why is that?
Update: (Code example from webdeveloper's solution below)
$.validator.unobtrusive.parse($('form'));
Example:
var saveAndUpdate = function (url) {
var myForm = $('form', $('#TheDivThatContainsTheNewHTML'));
$.ajax({
url: url,
type: 'POST',
data: myForm.serialize(),
success: function (result) {
$('#TheDivThatContainsTheNewHTML').html(result);
$.validator.unobtrusive.parse($('#TheDivThatContainsTheNewHTML'));
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
},
dataType: 'html'
});
}
But any reloading of the nested view with an ajax call, client side validation no longer works. Why is that?
Validation applies on document ready, when you refreshing page you should manually init validation for your form.
Like this:
$.validator.unobtrusive.parse("form");
Same question: jquery.validate.unobtrusive not working with dynamic injected elements

jquery form Submit success and Failure Callback

I'm building an ASP.Net Mvc 4 app. I see that i can use a #Ajax.BeginForm to perform a POST request asynchronously. Also API seems to have an OnSuccess and On Failure parameter, which takes in the javascript function to be executed on success/failure. I've read that this works for MS Ajax, but would this work for jquery as well ? I can't seem to get it working with jquery alone
#using (Ajax.BeginForm("Create", "Comment", null, new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "Post",
OnSuccess = "people.successfulSave",
OnFailure = "people.saveFailure"
},
If not then, i want to do it with jquery via form submit. Currently I'm doing
$('#commentSubmitInput').click(function() {
$("#commentForm").submit();
}
to submit the form. But in my controller I'm doing some model validation and return back Html with model errors if the model is invalid, else return a partial view with updated html. Now i read that i could bind the ajax call to a function with the below syntax
$("#commentForm").bind('ajax:complete', function () {
alert('bla');
});
but, is there a way I can have success and failure callback for form submit instead ?? kind of like the Jquery ajax call syntax
$.ajax({
url: $(this).attr('ajaxUrl'),
type: 'POST',
success: function (data) {
$("#comment_" + data.Id).remove();
},
error: function (data) {
window.location.reload();
}
});
Any help/suggestion is appreciated.
Thanks in advance !
As far as I can help you is to check this: ASP.NET MVC 4 - Ajax.BeginForm and html5
And maybe this (you can get an idea or two here): MVC4 - Ajax.BeginForm and Partial view gives 'undefined'

Loading Page for ASP.Net MVC

I'm using ASP.Net MVC to create a web site which needs to do some processing (5 - 10 seconds) before it can return a view to the user. Rather than leaving the user staring at the glacial progress bar I'd like to show some sort of "Please Wait/We'll be right back" animated gif to keep them interested.
Does anyone know a good approach to achieving this?
(I found this answer but its not quite what I need, this uses jQuery to fetch data once the view has been returned. I'd like to display the "Please Wait" while they're waiting for the view to appear)
Thanks
I think the solution you referenced will work for you. You just need to have your initial controller action return right away with the "please wait message", then have the AJAX call do the actual retrieval of the contents based on your processing. If the request really takes 5-10 seconds you may also need to adjust the timeout value on the AJAX request so that it is able to complete. I don't know what the default timeout is but is may be less than what you need.
EDIT Example:
View code:
<script type="text/javascript">
$(document).ready( function() {
$.ajax({
type: "POST",
url: '<$= Url.Action("GetSlowData","Controller") %>',
data: 'id=<%= ViewData["modelID"] %>',
timeout: 15000, // wait upto 15 secs
success: function(content){
$("#container").html(content);
}
});
});
</script>
...
<div id="#container">
Please wait while I retrieve the data.
</div>
Controller
public ActionResult ViewMyData( int id )
{
ViewData["modelID"] = id;
return View();
}
[AcceptVerbs( HttpVerbs.Post )]
public ActionResult GetSlowData( int id )
{
var model = ... do what you need to do to get the model...
return PartialView(model);
}
You'll also need a partial view (ViewUserControl) that takes your model and renders the view of the model. Note that this isn't complete -- you'll need to add error handling, you may want to consider what happens if javascript isn't enabled, ...

Resources