I am preparing one PhoneJS application. In that I am trying to put one simple butotn inside the view using the following code but not able to see that button and It's showing only loading icon...
home.html
<div data-options="dxView : { name: 'home', title: 'Home' } " >
<div class="home-view" data-options="dxContent : { targetPlaceholder: 'content' } " >
<p>Welcome</p>
<div data-bind="dxButton: { text: 'Click me!', clickAction: showHelloWorld }"></div>
</div>
</div>
home.js
MyApp.home = function (params) {
var viewModel = {
// Put the binding properties here
var showHelloWorld = function() {
alert("Hello world!");
};
ko.applyBindings(myViewModel);
return viewModel;
};
Anyone can help me please?
Your view model code is not well-formed:
MyApp.home = function () {
var viewModel = {
showHelloWorld: function() {
alert("Hello world!");
}
};
return viewModel;
};
viewModel should be valid js object.
You also shouldn't call applyBindings. It will be called by framework.
You should create the HtmlApplication and specify app routing. Not sure, maybe you've done it already.
Here is working fiddle:
http://jsfiddle.net/tabalinas/jb537/
Check out this tutorial "how to build you first PhoneJS app": http://phonejs.devexpress.com/Documentation/Tutorial/Getting_Started/Your_First_Application?version=13_2
Related
I have a few viewmodels, which contains a few functions like:
public override string ToString()
{
return $"{M_IV_ID} {M_IV_INVOICEAMOUNT} {M_IV_MANDANT} {M_IV_TOTALAMOUNT} {M_IV_VEHICLE_PURCHASE} {M_IV_URGENT}";
}
And update / insert functionalities. All of them work. I wrote them separately from my Asp.NET project and tested them since I wanted to do my back end first.
Now I tried to use those functions in my Asp.NET application:
First I get Data from the db in my Controller:
M_IV_INVOICE invoice = QueryBuilder.GetFirstOrDefault(new M_IV_INVOICE(), #"WHERE M_IV_ID IN (75693)");
And pass it to my view:
public ActionResult Index()
{
return View(invoice);
}
Now I tried to use my toString() method just to see if it works:
<form id="formUpdate" runat="server">
<div>
<asp:button id="Button" class="btn btn-primary" runat="server">Update</asp:button>
</div>
</form>
#{
string MyFunction()
{
return Model.ToString();
}
}
#section Scripts
{
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function () {
var button = document.getElementById('Button');
button.addEventListener('click', function () {
var test = "#MyFunction()";
console.log(test);
});
});
</script>
}
And if I do this, it works, and I get my model values printed in the browser console.
If I try to use my Update function instead of the toString() method:
public bool Update()
{
using (IDbConnection conn = ConnectionManager.GetConnection())
{
try
{
conn.Query(QueryBuilder.BuildUpdateForEntity(this, string.Format(" WHERE {0} = {1}", GetKey().Item1, GetKey().Item2)));
return true;
}catch(Exception e)
{
// TODO: Exceptionhandling
}
}
return false;
}
I get a Ora Exception right when the page loads, no button click performed:
Oracle.DataAccess.Client.OracleException: ORA-00936: missing expression
I struggle with understanding why, though.
The select I perform in my controller to get the data in the first place is working just fine, and as I said, if I print my model on button click, it works too.
What am I missing?
Edit:
It seems like the function is directly called while the eventhandler is added and since it has no data at the time, the ORA error is occurring.
But why? I don't understand this behavior.
Another Edit:
It has indeed something to do with the model isn't ready or something:
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function () {
var button = document.getElementById('Button');
button.addEventListener('click', function () {
setTimeout(() => { console.log("#MyFunction()") }, 3000);
});
});
</script>
I added the delay and no error on loading the page.
But that would be just a band aid, not a solution.
If someone has an idea how to prevent that behavior, I would appreciate it.
The #{}symbol is used to write server-side C# or VB code with HTML code, so in the javascript, when you use the #MyFunction() function, the Myfunction will execute. You could set a break point in the MyFunction and the button click event to check it, no matter using the ToString() method or the Update() method, they will work when the DOMContent Loaded. So, when use the Update() method, you will meet the missing expression error.
Based on your description, you want to do some action (call the server-side function/method) when user clicks the button, right? If that is the case, I suggest in the controller you can add the Myfunction and Update action methods, then, in the button click event, you can use JQuery get(), post() or Ajax method to call the action method, refer the following code:
Controller:
[HttpPost]
public JsonResult AjaxMethod(string name)
{
PersonModel person = new PersonModel
{
Name = name,
DateTime = DateTime.Now.ToString()
};
return Json(person);
}
and View Page:
<input type="text" id="txtName" />
<input type="button" id="btnGet" value="Get Current Time" />
#section Scripts{
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(function () {
$("#btnGet").click(function () {
$.ajax({
type: "POST",
url: "/Test/AjaxMethod",
data: { name: $("#txtName").val() },
success: function (response) {
alert("Hello: " + response.name + " .\nCurrent Date and Time: " + response.dateTime);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
}
I am new to using Knockout.js and for that matter JavaScript as well. I went through their tutorials and tried to modify the example to load data from server as below. Can anyone please point what's wrong with my code
JavaScript:
jQuery(document).ready(function () {
MyViewModel = function()
{
var self =this;
self.name = ko.observable("");
self.getJson = function()
{
jQuery.ajax({
//Do all the work
success: function(data)
{
self.name = data.name;
}
});
}
}
myViewModelObj = new MyViewModel();
ko.applyBindings(myViewModelObj);
myViewModelObj.getJson();
});
View:
<h1 data-bind="text: name "></h1>
After you have declare an object to be an observable, it then becomes a native function to knockout. In order to update the value, use
self.name(data.name);
Otherwise you are overwriting the function.
var uri="#Url.Content("/Views/Shared/_LogOnPartial")";
$("#logindisplay").load(uri);
it give me error
Files with leading underscores ("_") cannot be served.
why the url don't work.
You can use following code to load Partial Views in ~/Views/Shared/ Folder.
<script type="text/javascript">
$(document).ready(function () {
$("#btnclick").click(function () {
var uri = '#Url.Content("_LogOnPartial")';
$("#logindisplay").load(uri);
});
});
</script>
HTML is,
<input type="button" id="btnclick" value="Load View" />
<div id="logindisplay">
</div>
You should use
"#Html.Partial("/Views/Shared/_LogOnPartial)
to load partial instead of #Url.Content("/Views/Shared/_LogOnPartial")
best practice is to define path for partials, Layouts & views earlier
in App_Start/RouteConfig write method like below
public static void RegisterViewEngines(ICollection engines)
{
/*
* {0} = view name
* {1} = controller name
*/
engines.Clear();
engines.Add(new RazorViewEngine
{
ViewLocationFormats = new[] { "~/Views/{0}.cshtml" },
MasterLocationFormats = new[] { "~/Views/Shared/{0}.cshtml" },
PartialViewLocationFormats = new[] { "~/Views/Partial/{0}.cshtml" }
});
}
then execute it in Globa.asax like
RouteConfig.RegisterViewEngines(ViewEngines.Engines);
then you can easily call partial like this
#Html.Partial("_LogOnPartial");
Do we have better ways to handle it?
#foreach (var item in Model)
{
<div id="divDetail#{#item.CategoryId}"/>
#Ajax.ActionLink(
item.CategoryName,
"GetDetails",
new { id = item.CategoryId },
new AjaxOptions() { UpdateTargetId = string.Format("divDetail{0}", item.CategoryId) })
}
</div>
}
I would use the HTML.ActionLink helper method to generate the link and then use my custom jQuery ajax call to get the data. The advantage of doing this is i have full control so that i can do some manipulation of the response data before showing in the detail div.
I added a CSS class to the link so that i can be more specific (in selection of element) when binding my functionality.
#foreach (var item in Model)
{
<div id='divDetail#(item.ID)'></div>
#Html.ActionLink(item.CategoryName, "GetDetails", new { #id = item.CategoryId}, new {#id= "link-"+item.CategoryId, #class="lnkItem" })
}
and the script is
<script type="text/javascript">
$(function () {
$(".lnkItem").click(function (e) {
e.preventDefault();
var itemId = $(this).attr("id").split("-")[1]
$.get($(this).attr("href"), { id: itemId }, function (data) {
//i am free to do anything here before showing the data !
$("#divDetail" + itemId).html(data);
})
});
});
</script>
I'm trying to throw up a dialog window in MVC without using an AjaxActionLink. I'm using jquery ui 1.8.13 in this example.
Please consider the following snippets:
public class ModalViewModel
{
public string Title { get; set; }
public string Description { get; set; }
}
And the controller:
private ActionResult GetVisitors(VisitorSearchViewModel model)
{
VisitorSearchResponse response =
.... Omitted for brevity
if (response.Success)
{
return View("VisitorList", response.Visitors.ToList());
}
else
{
return RedirectToAction("Error");
}
}
public PartialViewResult Error()
{
return PartialView("Modal",
new ModalViewModel()
{
Title = "Test Title",
Description = "Test Description"
});
}
And finally, the Modal shared view:
#model CraftTraxNG.Model.ViewModels.ModalViewModel
<script type="text/javascript">
$(document).ready(function () {
$("#errorMessage").dialog(
{ autoOpen: true,
title: '#Model.Title',
width: 500,
height: 100,
modal: true,
buttons:{ "OK": function () {
$(this).dialog("close"); }
}
});
});
<div id="errorMessage" style="display:none;">
#Model.Description
</div>
When an error is encountered, it'll write out the partial view contents; ie., it successfully creates the dialog window with the appropriate styles. My problem is I want render the partial view on something on the view I'm currently on. I've never used it in this fashion before. As of now, when it renders that partial view, I lose the contents of the view I'm currently on.
Typically, I can use an AjaxActionLink and just set a div tag I want the dialog to render to and either replace it or insert it after, before, etc.
In this case, I'm heading out to the service and grabbing a response server-side and if it's unsuccessful, I need a way to replace some div tag on the regular view with this partial view.
Any help is appreciated.
Thank you.
I have run into this issue and I have not yet come up with an ideal solution. Here is what I normally do.
Click Me
$(function() {
$("#loadsContentOrError").click(e){
e.preventDefault();
$.ajax({
url: '<%: Url.Action("Error") %>',
success: function(html) {
html = $(html);
if(html.find('.errorMessage').length > 0) {
$('#divToLoadContentTo").append(html);
} else {
$('#divToLoadContentTo").html(html);
}
}
});
});
});
This is pretty rough but it gives you a good starting point.