Here's the thing, I'm trying to update a view where an image and a DateTime are displayed.
I want the image and the time to update without reloading the page. So after some research I found that using an Ajax call should do it.
For some reason neither the time or the image update after the ajax call and I can't figure out why.
Am I missing something, or it's not the way I should do it?
Please keep in mind, I am new to asp.net and Ajax. Thanks :)
Here's my View with the Ajax script:
#model myApp.Models.ImageViewModel
#{
ViewBag.Title = "Image";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script>
function refreshImage() {
$.ajax({
//url: "/Controller/ActionName",
async: true,
url: '/Image/GetImage',
type: 'GET',
success: function () {
setTimeout(refreshImage, 5000);
}
});
}
$(document).ready(function () {
setTimeout(refreshImage, 5000);
});
</script>
<div>
<div class="panel panel-info">
<div class="panel-heading"><h4>Image</h4></div>
<div class="panel-body">
<div class="ImgContainer">
<img src=#Model.ImageUrl>
<div>#Model.LastUpdateDate</div>
</div>
</div>
</div>
</div>
And here's the controller method:
public ActionResult GetImage()
{
DateTime lastUpdate = System.DateTime.Now;
string imageUrl = "http://lorempixel.com/1920/1080/animals";
ImageViewModel image = new ImageViewModel(lastUpdate, ImageUrl);
Debug.WriteLine("test");
return View(image);
}
Change your ajax call to this
function refreshImage() {
$.ajax({
dataType:'image/jpg',
url: '/Image/GetImage',
type: 'GET',
success: function () {
setTimeout(refreshImage, 5000);
}
});
}
Ok so I figured out what was going on. Since the url I used wasn't changing I forced the refresh of the image with a dull parameter on the url and also got the time to update at the same time.
Now my ajax call look like this.
$.ajax({
//url: "/Controller/ActionName"
url: '/Image/GetImage',
type: 'GET',
success: function () {
var time = new Date().toLocaleString();
$("#imageCam").attr("src", "#Model.ImageUrl" + "?" + time);
document.getElementById("theTime").innerHTML = time;
setTimeout(refreshImage, 5000);
}
});
Hope this help someone in the future.
See this question for more info
How to reload/refresh an element(image) in jQuery
Related
Good day.
I want to know why is my project calling the wrong url? The code is:
SCRIPT
$.ajax({
type: "POST",
url: "/Application/Franchise",
data: JSON.stringify(sendInfo),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$('#myModal3').modal('hide'); //hide the modal
},
error: function () {
alert("Error while inserting data");
}
});
CONTROLLER
public class ApplicationController : Controller
{
public ActionResult Franchise()
{
return View();
}
}
I even tried changing the url by 'Url.Action("Franchise", "Application")' but still the system kept on bringing me to http://localhost:49267/Home/Franchise.
I can't understand what is wrong here. Is there a bug in jquery ajax url post?
Thanks in advance.
UPDATE
<button class="btn btn-success" type="button" id="btnCapture">Submit</button>
#section Scripts{
<script src="~/Scripts/webcam.min.js"></script>
<script src="~/Scripts/webcam.js"></script>
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
</script>
<script language="JavaScript">
function take_snapshot() {
Webcam.snap( function(data_uri) {
document.getElementById('results').innerHTML =
'<img id="base64image" src="' + data_uri + '"/>';
} );
}
</script>
<script>
$(document).on("click", ".open-camera", function () {
var myBookId = $(this).data('id');
$(".modal-body #franid").val(myBookId);
})
</script>
<script>
$(function(){
$('#btnCapture').on('click', function(){
var file = document.getElementById("base64image").src;
var franid = $("#franid").val();
var sendInfo = {
Imagee: file,
FranIDD: franid
};
$.ajax({
type: "POST",
url: "/Application/Franchise",
data: JSON.stringify(sendInfo),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$('#myModal3').modal('hide'); //hide the modal
},
error: function () {
alert("Error while inserting data");
}
});
});
});
</script>
}
This is all my code.
Ok. So I found my problem. It was in my controller.
In my controller I tried adding return RedirectToAction("Franchise", "Home"); after the save command. As soon as I commented this, everything worked.
Thanks for the help again guys.
Please use the browser to access directly, not from within the IDE directly access, from the localhost:49267 should be from the IDE access, and you will write URL as http://www.google.com try.
I have a problem that I was stacked on for a while. I am rather new to this stuff so please be patient. I think it is like very simple to solve but I am running circles now. My intention is to make a simple alert that informs that method was completed. As you can see below my first attempt was made with simple string and if statement. I dont want to reload the page any more but now I have a problem that method ends later than alert script starts.
So I have a controller:
[HttpPost]
public ActionResult Executor(LMCMainViewModel model)
{
var curlsExecutor = _curls;
var applicationPurgeCurl = curlsExecutor.GetApplicationCurl(model);
var temporary = model.SuccessExecutionStatus = curlsExecutor.CurlCaller(model.ApplicationList.ApplicationCurl);
var tempListOfApplications = PopulateModel(model);
model.ApplicationList.ListOfApplications = tempListOfApplications.ApplicationList.ListOfApplications;
model.SuccessExecutionStatus = temporary;
return View("ListOfApplications", model);
}
And I have my view:
#model LMC.Models.LMCMainViewModel
#{
ViewData["Title"] = "Liberation";
}
#using (Html.BeginForm("HeaderString", "LMC"))
{
}
#using (Html.BeginForm("Executor", "LMC", FormMethod.Post))
{
<div class="col-sm-2" asp-action="ListOfApplications">
#Html.DropDownListFor(x => x.ApplicationList.ChosenApplication, Model.ApplicationList.ApplicationListItem, new { #id = "DropdownID" })
</div>
<div class="col-sm-2 col-sm-push-5">
#Html.HiddenFor(x => x.ApplicationList.ApplicationListItem)
<input class="btn ctn-success" id="submit" type="submit" value="Submit" />
<button id="submitButtonAjax" type="button" class="btn btn-success">Ajax button</button>
<div class="col-sm-12">
#Html.Label(null, (Model.SuccessExecutionStatus ? "Success" : " "),
new { Style = Model.SuccessExecutionStatus ? "color: green;" : "color: red;" })
</div>
</div>
}
Than I tried to implement many variations of Ajax script but I got so twisted that I can't even post you the best one... One thing I know is that when I remove: #using (Html.BeginForm("Executor", "LMC", FormMethod.Post)) and try to place it into Ajax it simply doesn't work. My intention is to have something that would work like this:
<script type="text/javascript">
$("#submitButtonAjax").on("click", function () {
$.ajax({
type: 'POST',
url: "/LMC/Executor",
success: function () {
alert("Went well");
}
});
</script>
I tried to convert controller method return into Json but it didnt work as well. I would appreciate any advices, where I can read about anything similar(I am aware that there are probably many similar topics, but I wan't able to implement anything that was working into my code, because I find my question one step backwards in comparison to others), or maybe it is that easy and I am missing something and you can just post a solution. Anyway, many thanks for any help.
The ajax call should look like bellow
$( document ).ready(function() {
$("#submitButtonAjax").on("click", function () {
var postData = {
FirstPropertyOfTheModel: ValueForTheFirstProperty,
SecondPropertyOfTheModel: ValueForTheSecondProperty,
};
$.ajax({
type: 'POST',
url: "/LMC/Executor",
data:postData,
success: function () {
alert("Went well");
},
error: function () {
alert("Opssss not working");
}
});
});
});
data is the value for the model of ActionResult method of the controller. The FirstPropertyOfTheModel and SecondPropertyOfTheModel will be replaced by the name of property and assign the corresponding value respectably. At url you can use
'#Url.Action("Executor", "LMC")'
so the ajax will look like
$( document ).ready(function() {
$("#submitButtonAjax").on("click", function () {
var postData = {
FirstPropertyOfTheModel: ValueForTheFirstProperty,
SecondPropertyOfTheModel: ValueForTheSecondProperty,
};
$.ajax({
type: 'POST',
url: '#Url.Action("Executor", "LMC")',
data:postData,
success: function () {
alert("Went well");
},
error: function () {
alert("Opssss not working");
}
});
});
});
I have a button with the class "btn" and span with id "ajaxtest". When I click on the button I want to put text "test" in my span tag. And this to be done in ASP.NET MVC.
In the View I have the following ajax call:
<span id="ajaxtest"></span>
<input type="submit" class="btn" name="neverMind" value="Test BTN"/>
<script>
$(document).ready(function () {
$(".btn").click(function () {
$.ajax({
method: "get",
cache: false,
url: "/MyController/MyAction",
dataType: 'string',
success: function (resp) {
$("#ajaxtest").html(resp);
}
});
});
});
</script>
In MyController I have the following code:
public string MyAction()
{
return "test";
}
I know how Ajax works, and I know how MVC works. I know that maybe the error is because we are expecting something like this in the controller:
public ActionResult MyAction()
{
if (Request.IsAjaxRequest())
{
//do something here
}
//do something else here
}
But actually that is my problem. I don't want to call some partial View with this call. I just want to return some string in my span and I'm wondering if this can be done without using additional partial views.
I want to use simple function that will only return the string.
Change dataType: 'string' to dataType: 'text'
<script>
$(document).ready(function () {
$(".btn").click(function () {
$.ajax({
method: "get",
cache: false,
url: "/login/MyAction",
dataType: 'text',
success: function (resp) {
$("#ajaxtest").html(resp);
}
});
});
});
</script>
I check it my local it will work for me
I am trying to use ko.mapping to transform data to a viewmodel. The result come from an async call to a web service.
Simple view:
<div data-bind="with: myData">
<div data-bind="text: mapWidth"></div>
<div data-bind="text: mapHeight"></div>
<div data-bind="foreach: priceRanges">
<div data-bind="text: title"></div>
</div>
AND the view model is as follows:
var ViewModel = function() {
var self = this;
self.myData = null;
var data = {
action: 'GetPricePoints',
type: 'who cares'
};
$.ajax({
url: 'http://cdt.lotamore.com/api/imap',
data: { "": JSON.stringify(data) },
//async: false, // works!
async: true, // doesn't work!!!!!
type: 'post'
})
.done(function (data) {
self.myData = ko.mapping.fromJS(data);
})
.error(function (data) {
alertError(data);
})
.always(function () {
});
};
When I run this synchronously is works fine. However, when I run it asynchronously it doesn't update the myData within my view model.
I have created a fiddle here:
http://jsfiddle.net/jgergen/jF9pm/20/
I really don't want to make ajax calls that block the UI thread!
What am I doing wrong here?
Thanks,
Jim
Here is the solution:
I have changed the line:
self.myData = null;
to:
self.myData = ko.observable();
This is not all, I tried this before without favorable results. In addition to making myData observable, I had to change the way it is updated. Here is the new .done method:
.done(function (d) {
self.myData(ko.mapping.fromJS(d));
})
So, what I needed to do is treat this field as I would any other observable.
You can see it here at this new fiddle: http://jsfiddle.net/jgergen/jF9pm/47/
I hope that this helps more than me. I searched for a solution to this problem all over the web without any results. So here it is.
Thanks,
Jim
I have been working with MVC for the past few days.
I have a problem in one of my pages, i.e I have a page where q user enters the required details and uploads a file. I have two buttons named Upload for Uploading File and Create for creating new profile.
My Problem
My problem is I don't want to reload the whole page when user clicks on upload button. I was thinking of using an webmethod for fileupload.
I don't know if what am I doing wrong here
Can any one correct me
This is my Webmethod in my controller named Create
Controller
[WebMethod]
public string FileUpload(HttpPostedFileBase file, BugModel model)
{
BugModel bug = null;
if (file != null && file.ContentLength > 0)
{
string path = "/Content/UploadedFiles/" + Path.GetFileName(file.FileName);
string savedFileName = Path.Combine(System.Web.HttpContext.Current.Server.MapPath ("~" +path));
file.SaveAs(savedFileName);
BugAttachment attachment = new BugAttachment();
attachment.FileName = "~" + path.ToString();
bug.ListFile.Add(attachment);
model = bug;
}
return "FileUploaded";
}
used a script to call the method
Javascript
<script type="text/javascript">
function UploadFile() {
$.ajax({
type:"Post",
url: "LogABug/FileUpload",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("File Uploaded")
},
error: function () {
ErrorMessage("Try Again");
}
});
}
</script>
can any one tell me how can I do this ...if this is the wrong method correct me the right one with the ideas please
You are uploading the file separately. Therefore you will need two actions:
public string Something(BugModel model) for the model.
public string FileUpload(HttpPostedFileBase file) for the file
Now, I would use jQuery Form Plugin for ajax submitting. Here is an example:
<script type="text/javascript">
$(function () {
$("#file-upload-form").submit(function () {
$(this).ajaxSubmit({
target: "#message",
cache: false
});
return false;
});
});
</script>
#using(Html.BeginForm("FileUpload", "LogABug", FormMethod.Post, new { enctype = "multipart/form-data", id = "file-upload-form" })) {
#Html.ValidationSummary(true)
<fieldset>
#Html.EditorFor(model => model.File)
<input type="submit" value="Upload" />
</fieldset>
}
<div id="message">
</div>
What ever you return from your action will be displayed in the div with id message