I am trying to build a website that is hosted on Azure as a free website, it is using MVC4, with KnockoutMVC. The website is updating a table every 4 seconds from the controller. The code executes without problem locally, however when I deploy it to the Azure website, it does not process updates.
I now have started a completely new MVC 4 project, with some simple functions using knockout, showing the current time, and updating this every .5 of a second from the controller, it is using the same structure as the javascript I have written for the proper website. It is giving the same problem, and it appears as if the ko.ServerAction call is halting the javascript function.
View
#using PerpetuumSoft.Knockout
#model MVCHelloWorld.Models.HelloWorldModel
#{
var ko = Html.CreateKnockoutContext();
}
<script type="text/javascript">
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
#ko.ServerAction("Index", "HelloWorld");
t = setTimeout(function() { startTime(); }, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
</script>
<body onload="startTime()">
<h2>Hello World - 2</h2>
<div id="time"></div>
<label>Knockout time</label>
#ko.Html.Span(m => m.Time)
</body>
#ko.Apply(Model)
Controller
namespace MVCHelloWorld.Controllers
{
public class HelloWorldController : BaseController
{
public HelloWorldModel model = new HelloWorldModel();
public ActionResult Index()
{
GetTimeDoCalculation();
return View();
}
public void GetTimeDoCalculation()
{
model.Time = DateTime.Now.ToString("H:mm:ss");
}
}
}
Model
namespace MVCHelloWorld.Models
{
public class HelloWorldModel
{
public string Time { get; set; }
}
}
Try adding this to the body of your view:
<script type="text/javascript">
#* Replace 4000 with the timeout, in milliseconds *#
window.setInterval(startTime, 4000)
</script>
Your entire view will look like this:
#using PerpetuumSoft.Knockout
#model MvcApplication2.Models.HelloWorldModel
#{
var ko = Html.CreateKnockoutContext();
}
<script type="text/javascript">
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
#ko.ServerAction("Index", "HelloWorld");
t = setTimeout(function() { startTime(); }, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
</script>
<body onload="startTime()">
<h2>Hello World - 2</h2>
<div id="time">
<script type="text/javascript">
#* Replace 4000 with the timeout, in milliseconds *#
window.setInterval(startTime, 4000)
</script>
<label>Knockout time</label>
#ko.Html.Span(m => m.Time)
</div>
</body>
#ko.Apply(Model)
Related
my partial view work quickly and well when run it local but when Publish it on server my partial view work very slowly and website is heavy
my partial code is
<script type="text/javascript">
function Son(id)
{
this.id_ = id;
var d = 'div#' + id_;
var urId = '#Url.Action("Son","Tree")';
$(d).load(urId , {id:id_}).ajaxSuccess();
//Son2(id);
}
</script>
<script type="text/javascript">
function Son2(id)
{
this.id_ = id;
var urId2 = '#Url.Action("DivSon","Tree")';
$('div.inn_height').load(urId2 , {id:id_}).ajaxSuccess();
}
</script>
#{ var father = Model.Where(a => a.Parent_Id == 0).FirstOrDefault();
var main = Model.Where(a => a.Parent_Id == father.id).ToList();}
<ul class="list_family">
#if (main.Count() > 0)
{
for (int i = 0; i < main.Count(); i++)
{
var item = main.ElementAt(i);
<li id="#item.id">
<div>
<div class="manu">
#if (item.Wife_Image != null)
{
<div class="wife"><img class="img_wife" src="#Url.Content(item.Wife_Image)"></div>
}
#if (item.Wife_Image == null && item.IsMarried=="forsale")
{
<div class="wife"><img class="img_wife" src="~/Content/img/visa.png" style="visibility:hidden"></div>
}
<a onclick="Son('#item.id');Son2('#item.id');">
<img src="#Url.Content(item.Image)">
</a>
</div>
<i><strong>#item.Name</strong></i>
</div>
</li>
}
}
</ul>
c#
family2016Entities db = new family2016Entities();
[OutputCache(Duration = 10, Location = System.Web.UI.OutputCacheLocation.ServerAndClient)]
public ActionResult Index()
{
return View(db.Trees.OrderByDescending(a => a.id));
}
[OutputCache(Duration = 10, Location = System.Web.UI.OutputCacheLocation.ServerAndClient)]
public ActionResult Son(int id)
{
ViewBag.Grand = id;
var child = db.SELECTTreeSonrecords(id).ToList();
return PartialView("Son", child);
}
[OutputCache(Duration = 10, Location = System.Web.UI.OutputCacheLocation.ServerAndClient)]
public ActionResult DivSon(int id)
{
ViewBag.Grand2 = id;
var details = db.SELECTTreerecords(id).FirstOrDefault();
return PartialView("DivSon", details);
}
what can i do to make my partial view work quickly when publish it
and What's the alternative for partial view to work well
I want to get the ID from URL in ASP.NET MVC Controller and insert it into Project_ID, the bellow is my code, i tried but its now working for me.
http://localhost:20487/ProjectComponent/Index/1
My Controller
[HttpPost]
public JsonResult SaveComponent(OrderVM O, int id)
{
bool status = false;
if (ModelState.IsValid)
{
using (Entities db = new Entities())
{
ProjComponent ProjComponent = new ProjComponent { project_id = id, title = O.title, description = O.description };
foreach (var i in O.ProjComponentActivities)
{
ProjComponent.ProjComponentActivity.Add(i);
}
db.ProjComponents.Add(ProjComponent);
db.SaveChanges();
status = true;
}
}
}
You can always use a hidden field and update it by jquery/javscript and send it to back end in ajax helper.....
Make sure 1.name should be exactly name as ActionMethod param and 3.Jquery ,jQuery Validate and jQuery unobstrusive ajax is loaded correctly
My code .cshtml
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<div>
#{
AjaxOptions options = new AjaxOptions();
options.HttpMethod = "POST";
options.OnBegin = "OnBeginRequest";
options.OnSuccess = "OnSuccessRequest";
options.OnComplete = "OnCompleteRequest";
options.OnFailure = "OnFailureRequest";
// options.Confirm = "Do you want to Add Country ?";
options.UpdateTargetId = "divResponse";
options.InsertionMode = InsertionMode.InsertAfter;
}
#using (Ajax.BeginForm("AjaxSend", "Stackoverflow", options))
{
<input type="hidden" name="project_id" id="project_id" value="project_id" />
<input type="submit" value="Click me" />
}
</div>
<div id="divResponse">
</div>
<script>
$(function() {
var url = window.location.href;
var array = url.split('/');
var lastsegment = array[array.length - 1];
console.log(lastsegment);
$('#project_id').val(lastsegment);
});
function OnBeginRequest() {
console.log('On Begin');
}
function OnCompleteRequest() {
console.log('On Completed');
}
function OnSuccessRequest() {
console.log('On Success');
}
function OnFailureRequest() {
console.log('On Failure');
}
</script>
and Controller
[HttpPost]
public JsonResult AjaxSend(String project_id)
{
//rest goes here
return Json(new { Success = true });
}
this link may help link
you can get the id from URL Like This:
Cotroller:
public ActionResult Index(int id)
{
ViewBag.ID = id;
Your Code......
return View(...);
}
View:
#{
ViewBag.Title = "Index";
var ID = ViewBag.ID;
}
Now you have an ID in the variable
I have a controller
public class AccountDetailsController : Controller
{
private readonly IAccountStatsRepository _accountStatsRepository;
public AccountDetailsController(IAccountStatsRepository accountStatsRepository)
{
_accountStatsRepository = accountStatsRepository;
}
public ActionResult Details(string accountEmail)
{
var stats = _accountStatsRepository.Get(accountEmail);
var accountDetailsViewModel = new AccountDetailsViewModel
{
Email = accountEmail,
Money = stats.TotalCredits
};
return View(accountDetailsViewModel);
}
[OutputCache(NoStore = true, Location = OutputCacheLocation.Client, Duration = 3)] // every 3 sec
public ActionResult GetLatestLogging(string email)
{
//if (email == null || email != null)
//{
var list = new List<LogViewModel>();
return PartialView("LatestLoggingView", list);
//}
}
}
And a View
#using FutWebFrontend.ViewModels
#model AccountDetailsViewModel
#{
ViewBag.Title = "Details";
}
<h2>#Model.Email</h2>
<div>
<h4>Account details</h4>
Money #String.Format("{0:0,0}", Model.Money)
</div>
<div id="loggingstream">
#Html.Partial("LatestLoggingView", new List<LogViewModel>())
</div>
<hr />
<dl class="dl-horizontal"></dl>
<p>
#Html.ActionLink("Back to List", "index", "AccountControl")
</p>
<script type="text/javascript">
$(function() {
setInterval(function () { $('#loggingstream').load('/AccountDetails/GetLatestLogging/#Model.Email'); }, 3000);
});
</script>
But when I go to my page and put a breakpoint in GetLatestLogging then nothing happens
If I hit F12 in chrome I get "Uncaught ReferenceError: $ is not defined "Details:67
From what I can gather, this should hit my Get method every 3 seconds, but I must have made a simple error somewhere
Try this
$( document ).ready(function() {
setInterval(function () {$('#loggingstream').load('/AccountDetails/GetLatestLogging/#Model.Email'); }, 3000);
});
I have a controller with an Index action which returns a ViewModel and a GetCategories action which should return a partial view.
So here is my CategoryController.cs file:
public class CategoryController : Controller
{
public ActionResult Index()
{
CategoryViewModel ob = new CategoryViewModel();
ob.LoadLanguages();
return View(ob);
}
public ActionResult GetCategories(int langID)
{
CategoryViewModel ol = new CategoryViewModel();
ol.LoadCategoriesByLanguage(langID);
if (Request.IsAjaxRequest())
return PartialView("GetCategories",ol);
In my Index.cshtml view I create a dropdown list and, when the user selects an element, it makes an Ajax request to the getCategories action and on success I should load the GetCategories partial view. The problem is that it redirects me to a new page and I can no longer see my dropdown.
Here is my Index.cshtml file:
#model Onion.Web.ViewModels.CategoryViewModel
<script>
$(document).ready(function () {
$("#ddlLanguages").change(function () {
$.ajax({
type: 'GET',
url: '#Url.Action("GetCategories")' + '?langId=' + this.value,
data: {},
success: callbackFuntion('#Url.Action("GetCategories")' + '?langId=' + this.value),
error: function () { alert('Error'); }
});
});
});
function callbackFuntion(url){
window.location = url;
}
</script>
#Html.DropDownList("Languages", new SelectList(Model.lstLanguages, "LanguageID", "Name"), "SELCT LANGUAGE----->",new { id = "ddlLanguages" })
}
And here is my Category.cshtml file:
#model Onion.Web.ViewModels.CategoryViewModel
<table>
<tr>
<td>ID</td>
<td>Title</td>
</tr>
#foreach (var item in Model.lstCategoryLanguages)
{
<tr>
<td>#item.Title</td>
<td>#item.ShortDescription</td>
</tr>
}
</table>
I can't beleve how easy it is in web forms and here i'm struggling for hours. Is there a better way to do all this. Thank you in advance
I slightly modified your Models and made it working prototype, from here you can get the concept and apply it to your models -
Models -
public class CategoryViewModel
{
public List<string> DDLItems { get; set; }
}
public class CategoryNewViewModel
{
public string Name { get; set; }
}
Controller -
public class MyPartialController : Controller
{
public ActionResult Index()
{
CategoryViewModel ob = new CategoryViewModel();
ob.DDLItems = new List<string>();
ob.DDLItems.Add("1");
ob.DDLItems.Add("2");
ob.DDLItems.Add("3");
return View(ob);
}
public ActionResult GetCategories(int langID)
{
CategoryNewViewModel ol = new CategoryNewViewModel();
if (langID == 1)
ol.Name = "One";
else if (langID == 2)
ol.Name = "two";
else
ol.Name = "three";
return PartialView("GetCategories", ol);
}
}
Index View -
#model MVC.Controllers.CategoryViewModel
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function () {
$("#DDLCategories").change(function () {
$.ajax({
type: 'GET',
url: '#Url.Action("GetCategories")',
data: {langID : $('#DDLCategories').val()},
success: function (result) { $('#container').html(result); },
error: function () { alert('Error'); }
});
});
});
</script>
<h2>Index</h2>
#Html.DropDownList("DDLCategories", new SelectList(Model.DDLItems), "--Choose any Item--")
<div id="container"> </div>
GetCategories Partial View -
#model MVC.Controllers.CategoryNewViewModel
#Model.Name
When you select a item in Dropdownlist, then the corresponding partialview will be loaded in the div.
Output -
It's normal because you execute a redirection in your success callback.
You can use load function of jQuery to load your partial view in a div of your dom.
<div id="categoriesPlace"></div>
<script>
$(document).ready(function () {
$("#ddlLanguages").change(function () {
$("#categoriesPlace").load('#Url.Action("GetCategories")' + '?langId=' + this.value, function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
alert( msg + xhr.status + " " + xhr.statusText );
}
}
});
});
</script>
I am developing MVC app.
In the view, I have declare some variable and I want to use it in the Jscript.
#model PaymentAdviceEntity.EMI
#{
ViewBag.Title = "Create";
double TotalAmt = 0;
}
#using (Html.BeginForm("Edit", "EMI", FormMethod.Post, new { #id = "frmEdit" }))
{
#if (Model.EMI_Child.Count > 0)
{
#foreach (var PaidEMIList in Model.EMI_Child)
{
TotalAmt = TotalAmt + PaidEMIList.Amount;
}
}
}
<script>
$(document).ready(function () {
CheckBalAmt();
});
function CheckBalAmt()
{
var nTotalAmount = document.getElementById("TotalAmount").value;
var nAllreadyPaidAmount = document.getElementById("AllreadyPaidAmount").value;
var BalAmt = nTotalAmount - nAllreadyPaidAmount;
var totalAmt1 = #TotalAmt; <- Shows error here...
var BalAndTotalAmt = BalAmt +totalAmt1;
$('.BalanceAmt').text("Bal Amt. : " + BalAndTotalAmt );
}
</script>
in above CheckBalAmt() method I want to show the value of variable TotalAmt ...
but it dont show anything...
var totalAmt1 = ('#TotalAmt');
var BalAndTotalAmt = BalAmt - totalAmt1;
alert(#TotalAmt);
$('.BalanceAmt').text("Bal Amt. : " + BalAndTotalAmt );
this code works...
function CheckBalAmt()
{
alert('#TotalAmt');
}
You have to use the razor symbol