This sytax is in razor that I am converting to knockoutJS.. any help much appreciated..
Where ItemStatus.Active is 0 in an enum in c# ( backend )
#foreach (var employee in Employees.Where(x => x.Status == ItemStatus.Active))
{
<div class="someclass”>
<span class="label">Name:</span>
<span class="value">#employee.Name</span>
</div>
}
How do I replicate this logic in knockout foreach, ie I only want to show employees who are currently active or employed
Thank you
Any JavaScript expression can be used in Knockout bindings.
So you could use the filter function (ES6):
<!-- ko foreach: Employees.filter(employee => employee.Status == 0) -->
...
<!-- /ko -->
Or any other method of filtering:
<!-- ko foreach: ko.utils.arrayFilter(Employees.filter, function(employee) { return employee.Status == 0; }) -->
...
<!-- /ko -->
Razor runs server-side. So, you can't use Employees with knockout bindings which are apllied client-side. You need to hand over this Employees data to a javascript variable, and then bind that using knockout which will run client-side, after the page loads.
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script>
// cretes a js array of active employees
var activeEmployees = #Html.Raw(JsonConvert.SerializeObject(Employees.Where(x => x.Status == ItemStatus.Active)));
var viewModel = {
Employees: ko.observableArray(activeEmployees)
}
ko.applyBindings(viewModel);
</script>
Use the foreach binding in your HTML like this (Here Employees refers to the property of your knockout viewModel, not MVC)
<!-- ko foreach: Employees -->
<div class="someclass">
<span class="label">Name:</span>
<span class="value" data-bind="text:Name"></span>
</div>
<!-- /ko -->
You also need to add #using Newtonsoft.Json to the top your cshtml file for JsonConvert
Related
I am trying to concatenate a base path of image folder with a complete path coming from a DB in a .cshtml file to show image on the page but nothing is working out in my end. The best solution that I have tried is,
#foreach (var item in Model)
{
string img = #"~/pics"+Html.DisplayFor(modelItem=>item.ImagePath);
<article>
#*My Dynamic Article*#
<div class="content">
<h3>#Html.DisplayFor(modelItem => item.Name)</h3>
<img src="#img" width="95%" alt="Laser" />
<p>Hello</p>
</div>
</article>}
But this too is outputting something strange, I see this path in the output on web browser,
<img src="~/picsMicrosoft.AspNetCore.Mvc.ViewFeatures.StringHtmlContent" width="95%" alt="Laser" />
Tell me some method that works fine with asp.net core MVC latest release. Thanks
To solve this problem, you can put the content of the img variable directly into the src attribute, and add the # symbol directly in front of Html.DisplayFor(modelItem=>item.ImagePath).
Here is the work code:
#foreach (var item in Model)
{
<article>
#*My Dynamic Article*#
<div class="content">
<h3>#Html.DisplayFor(modelItem => item.Name)</h3>
<img src="~/pics/#Html.DisplayFor(model =>item.ImagePath)" width="95%" alt="Laser" />
<p>Hello</p>
</div>
</article>}
Or you can directly get ImagePath by following:
<img src="~/pics/#item.ImagePath" width="95%" alt="Laser" />
Here is the test result:
<c:forEach items="${customer.iscutomer}">
<div>
<i>${customer.customerNumber}. </i>
<li>
${customer.customerName}
</li>
</div>
</c:forEach>
i don't know how to get customer name in Struts2 when user selects any hyerlink(customer name come from customer object).
You can use Struts anchor tag and add parameter to the URL.
<s:a href="url"><s:param name="customerName">${customer.customerName}</s:param>CustomerName</s:a>
Note, that you can use EL in the body of the tag.
May be this can help you to start:
<c:forEach items="${customer.iscutomer}">
<div>
<i>${customer.customerNumber}. </i>
<li>
<s:a name="foo" namespace="bar">
<s:param name="customerName">${customer.customerName}</s:param>
<s:param name="customerNubmber">${customer.customerNumber}</s:param>
</s:a>
</li>
</div>
Please consider I find that the s:a url does not add parameters to link. Now your generated link will be /foo/bar/action?customerName=joe&customerNumber=1
No in your JS you can have:
$('a').bind('click',function(){
var url = ($(this).attr('href'));
var customerName= getURLParameter(url, 'customerName');
var customerNumber= getURLParameter(url, 'customerNumber');
//calling the ajax function
pop(cat, typ)
});
If you want to have ajax calls please have a look at struts 2 jquery plugin.
I have an ASP.NET MVC site and I am trying to get knockout-mvc working with it.
I have created a View Model in the C# code called Refund that contains among other things a Voucher called Vouchertype and a List<Country> called Countries. Voucher has a variable of type int called VoucherNumber
This View Model is passed into a strongly defined view Refund\Index
I am trying to get knockout-mvc to bind the values in Refund.Voucher.VoucherNumber to a textbox, and the Values in Refund.Countries to a drop-down list. On the controller I have hardcoded the values of Voucher.Vouchernumber and added two countries to the Country list.
Here is my View Code:
#using Resources
#using PerpetuumSoft.Knockout
#model MVC.Models.RefundViewModel
#{
var ko = Html.CreateKnockoutContext();
}
<div id="refundformcontainer">
<div id="headersection">
<div id="pagetitlecontainer">#Language.RefundVouchers</div>
<div id="helpercontainer">
<label id="lblhelper">To begin enter a voucher number or scan a barcode</label>
</div>
</div>
<div id="vouchercontainer">
<div id="voucherdetailscontainer">
<h5>#Language.VoucherDetails</h5>
<div id="vouchernumbercontainer" class="initialvoucherfield">
#Html.LabelFor(x=>x.Voucher.VoucherNumber)
#ko.Html.TextBox(x=>x.Voucher.VoucherNumber)
</div>
<div id="countrycontainer" class="initialvoucherfield">
#Html.LabelFor(x=>x.Voucher.Country)
<select ko.Bind.Options(x=>x.Countries).OptionsText("Name").OptionsValue("CountryId").Value(x=>x.Voucher.CountryId) ></select>
</div>
</div>
</div>
</div>
#ko.Apply(Model);
When the page loads, neither controls are bound to.
When I look at the generated source the following code is generated
<script type="text/javascript">
var viewModelJs = {"Refund":null,"Voucher":{"VoucherId":0,"VoucherNumber":123456789,"Country":null,"CountryId":0,"Retailer":null,"RetailerId":0,"PurchaseDate":"0001-01-01T00:00:00","CustomsStampDate":null,"InvoiceNumber":"","LineItems":[],"TotalPurchasePrice":0.0},"Countries":[{"CountryId":380,"Name":"Italy"},{"CountryId":724,"Name":"Spain"}]};
var viewModel = ko.mapping.fromJS(viewModelJs);
ko.applyBindings(viewModel);
</script>
knockout-2.2.0.js and knockout.mapping-latest.js are both included in the page
The error I am getting is
0x800a139e - JavaScript runtine error: Unable to parse bindings
Message: [Object Error]
Bindings value: Voucher().VoucherNumber
I then changed the Refund View model so it had a property VoucherNumber and had the textbox reference this instead of the Voucher.VoucherNumber property
#ko.Html.TextBox(x=>x.VoucherNumber)
When I ran this I got the same unable to parse bindings error, but this time for the country
Bindings value: options : Countries, optonsText : Name, optionsValue : CountryId
Does anybody have any idea what is causing this?
i think, this should work.
<select #ko.Bind.Options(x=>x.Countries).OptionsText("'Name'").OptionsValue("'CountryId'").Value(x=>x.Voucher.CountryId) ></select>
I am trying to build a JQuery Mobile UI which uses upshot for getting data from the service and then uses Knockout.js to bind the values to a list. I am able to populate the data however, the JQuery mobile styles are not getting rendered.
Here is my code. Any help in this regard would be really appreciated.
<h2>Projects (<span data-bind="text: projects().length"></span>)</h2>
<ul data-inset="true" data-bind="foreach: projects" data-role="listview" data-theme="e" data-dividertheme="c" data-filter="true">
<li>
Project Type : <label data-bind="text: ProjectType"></label>
Description : <label data-bind="text: Description"></label>
</li>
</ul>
<p></p>
#(Html.UpshotContext(bufferChanges: true).DataSource<ProjectServiceController>(x => x.GetProjects()))
<script type="text/javascript">
$(function () {
var dataSource = upshot.dataSources.Projects.refresh();
var ProjectsViewModel = {
projects: dataSource.getEntities()
};
ko.applyBindings(ProjectsViewModel);
});
</script>
The refresh() call is asynchronous, so you can provide a callback function that is executed after the refresh. jQueryMobile docs say that if you add items you need to refresh the listview after the items are created: http://jquerymobile.com/demos/1.0.1/docs/lists/docs-lists.html
Here's an example of how you might do that:
var dataSource = upshot.dataSources.Projects.refresh(function() {
$("ul").listview('refresh');
});
I Am Using asp.net mvc3 . I am rendering a partial view by using foreach loop . So the thing i want to do is that i have a div in my partial view every time when partial rendered a new div is placed into the page . I just want to give every div a unique name . Can Anyone Help Me Out ??????
Thanks In Advance
Just make sure you have something in the model used by your partial view that is unique - then in your partial view all you need is
<div name="div_#(Model.SomeUniqueId)"></div>
If there is nothing appropriate in the model, you can use the ViewBag:
#{
var i = 0;
foreach (var item in Model.Items) {
ViewBag.UniqueId=i++;
Html.RenderPartial("PartialView", item);
}
}
in your partial view, you could have the div defined as per below:
<div id="<%=Guid.NewGuid().ToString() %>"></div>
that way, you don't have to care about the model doing any extra lifting to populate the div id. also, note that i used id as the unique placeholder. divs don't have a 'name' attribute, so be careful to make a note of that.
You need to create DIV dynamically with the help of javascript
Following is the sample code that will help you
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Create DIV Dynamically Using JavaScript</title>
<script type="text/javascript" language="javascript">
function DynamicDiv() {
var dynDiv = document.createElement("div");
dynDiv.id = "divDyna";
dynDiv.innerHTML = "Created using JavaScript";
dynDiv.style.height = "20px";
dynDiv.style.width = "300px";
dynDiv.style.backgroundColor = 'gray';
document.body.appendChild(dynDiv);
}
</script>
</head>
<body>
<div>
<input id="Button1" type="button"
value="Using JS" onclick="DynamicDiv();" />
</div>
</body>
</html>