RouteLink with Knockoutjs template item properties - asp.net-mvc-4

I have a template rendering another template via foreach: viewModel.foos. On this template I would like to do something like this: #Html.RouteLink("View", "Foo", new { id = fooId, text = fooName }). Being fooId and fooName properties of the view model.

I've added this to my template:
<a data-bind="attr: { href: Url }">View</a>
And this to my Foo object:
public class Foo : FooBase {
public long FooId { get; set; }
public string FooName { get; set; }
public string Url {
get {
return string.Format("/foo/{0}/{1}", FooId, FooName
}
}
}
The cons:
Painfully scalable.
The pros:
Simplicity.

This does not answer question, but I will keep it here because it shows how you can do it for a more SPA like approuch.
If you are looking to move navigation to client check out Durandal or my light weight SPA engine
https://github.com/AndersMalmgren/Knockout.Bootstrap.Demo
Old answer before question was updated
You have to do this from your model (Which is a good thing because it should not be done in the view)
Let your subview model take the parameters as constructor arguments
MyViewModel = function() {
this.subView = ko.observable();
};
MyViewModel.prototype = {
loadSubView: function() {
this.subView(new SubViewModel(this.params));
}
};
edit: Tip test this lib for templating
http://jsfiddle.net/hwTup/

Related

passing blazor parameters to another page

I have been trying to pass parameters trough another page and this works, however i'm not getting what I desired and it has probably to do with what i pass.
The first thing i pass is a name but includes spaces and special character, the second thing i pass is a web link
how i send it:
<div class="col-sm-4">
<h3>Programming</h3>
#if (programming == null)
{
<p><em>Loading...</em></p>
}
else
{
foreach (var program in programming)
{
#program.Name
<br />
}
}
</div>
where it goes to
#page "/CourseDetails"
#using Portfolio.Models;
#using Portfolio_Frontend.Data;
#using Microsoft.AspNetCore.WebUtilities
#inject NavigationManager NavigationHelper
<h3>CourseDetails</h3>
#if (Name == null)
{
<p><em>Loading...</em></p>
}
else
{
<p>#Name</p>
}
#code {
public string Name { get; set; }
protected override void OnInitialized()
{
var uri = NavigationHelper.ToAbsoluteUri
(NavigationHelper.Uri);
if (QueryHelpers.ParseQuery(uri.Query).
TryGetValue("name", out var name))
{
Name = name.First();
}
}
}
i tried parameters as well and now tried query string gives the same result.
the name it should pass in this particular case is: C# Intermediate: Classes, Interfaces and OOP
What i get is only 'C' I assume because it is not able to translate the #.
is there a way to pass literal strings?
where it goes to: https://localhost:5105/CourseDetails/?name=C#%20Intermediate:%20Classes,%20Interfaces%20and%20OOP
this seems right to me.
Minor correction of URL syntax methodology
You have:
#program.Name
Which has a URL of /CourseDetails/?name=C#
Normally, you would do either
/CourseDetails/C#
/CourseDetails?name=C#
Except, Blazor doesn't explicitly support optional route parameters (/CourseDetails?name=C#)
REF: https://blazor-university.com/routing/optional-route-parameters/#:~:text=Optional%20route%20parameters%20aren%E2%80%99t%20supported%20explicitly%20by%20Blazor,,then%20replace%20all%20references%20to%20currentCount%20with%20CurrentCount.
It looks as though you can keep the optional query parameters and fiddle with the QueryHelpers.ParseQuery() I don't quite buy into that but if you want to keep going that route check out this post by #chris sainty
Link: https://chrissainty.com/working-with-query-strings-in-blazor/
I would much rather create a new model (DTO) that knows exactly how to display the CourseDetails name in a URL encoded fashion for the link, and the display name for the user.
public class ProgramModel
{
private readonly string name;
public ProgramModel(string name)
{
this.name = name;
}
public string DisplayName => name;
public string RelativeUrl => HttpUtility.UrlEncode(name);
}
And when we need to render the links on the 'Courses' page, it would look like this:
#page "/courses"
#using BlazorApp1.Data
<div class="col-sm-4">
<h3>Programming</h3>
#foreach (var program in programming)
{
#program.DisplayName
<br />
}
</div>
#code {
public IEnumerable<ProgramModel> programming { get; set; }
protected override void OnInitialized()
{
programming = new List<ProgramModel>()
{
new ProgramModel("Rust Things"),
new ProgramModel("JavaScript Things"),
new ProgramModel("C# Things")
};
}
}
And finally, when displaying the CourseDetails page, we can simply decode the name from the URL with the same utility that encoded the string in the first place, instead of guessing whether or not it's the apps fault, or the browsers fault that the '#' is not getting encoded properly to '%23'
#page "/CourseDetails/{Name}"
#inject NavigationManager NavigationHelper
#using System.Web
<h3>CourseDetails</h3>
<p>#HttpUtility.UrlDecode(Name)</p>
#code {
[Parameter]
public string Name { get; set; }
}
I recommend letting go of the idea of navigating from page to page, and using components:
<div>
#if (SelectedItem is not null)
{
<MyResultsPage SelectedProgramClass=#SelectedItem />
}
</div>
#code
{
ProgramClass SelectedItem {get; set;}
void SomeWayToSelectMyItem(ProgramClass newSelection){
SelectedItem = newSelection;
StateHasChanged();
}
}
Then in your display page, MyResultsPage.blazor
<div>
<div>#SelectedProgramClass.name</div>
. . .
</div>
#code {
[Parameter]
ProgramClass SelectedProgramClass{get; set;}
}
<MyResultsPage> will not show up in any way on the client, or even be initialized, until you've assigned something to SelectedProgramClass.

Localized page names with ASP.NET Core 2.1

When create a Razor page, e.g. "Events.cshtml", one get its model name set to
#page
#model EventsModel
where the page's name in this case is "Events", and the URL would look like
http://example.com/Events
To be able to use page name's in Norwegian I added the following to the "Startup.cs"
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddRazorPagesOptions(options => {
options.Conventions.AddPageRoute("/Events", "/hvaskjer");
options.Conventions.AddPageRoute("/Companies", "/bedrifter");
options.Conventions.AddPageRoute("/Contact", "/kontakt");
});
With this I can also use an URL like this and still serve the "Events" page
http://example.com/hvaskjer
I'm planning to support many more languages and wonder, is this the recommended way to setup localized page name's/route's?, or is there a more proper, correct way to accomplish the same.
I mean, with the above sample, and having 15 pages in 10 languages it gets/feels messy using options.Conventions.AddPageRoute("/Page", "/side"); 150 times.
You can do this with the IPageRouteModelConvention interface. It provides access to the PageRouteModel where you can effectively add more templates for routes to match against for a particular page.
Here's a very simple proof of concept based on the following service and model:
public interface ILocalizationService
{
List<LocalRoute> LocalRoutes();
}
public class LocalizationService : ILocalizationService
{
public List<LocalRoute> LocalRoutes()
{
var routes = new List<LocalRoute>
{
new LocalRoute{Page = "/Pages/Contact.cshtml", Versions = new List<string>{"kontakt", "contacto", "contatto" } }
};
return routes;
}
}
public class LocalRoute
{
public string Page { get; set; }
public List<string> Versions { get; set; }
}
All it does is provide the list of options for a particular page. The IPageRouteModelConvention implementation looks like this:
public class LocalizedPageRouteModelConvention : IPageRouteModelConvention
{
private ILocalizationService _localizationService;
public LocalizedPageRouteModelConvention(ILocalizationService localizationService)
{
_localizationService = localizationService;
}
public void Apply(PageRouteModel model)
{
var route = _localizationService.LocalRoutes().FirstOrDefault(p => p.Page == model.RelativePath);
if (route != null)
{
foreach (var option in route.Versions)
{
model.Selectors.Add(new SelectorModel()
{
AttributeRouteModel = new AttributeRouteModel
{
Template = option
}
});
}
}
}
}
At Startup, Razor Pages build the routes for the application. The Apply method is executed for every navigable page that the framework finds. If the relative path of the current page matches one in your data, an additional template is added for each option.
You register the new convention in ConfigureServices:
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.Add(new LocalizedPageRouteModelConvention(new LocalizationService()));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

Nested objects in view model confuses MVC 4 routing?

So I have this view and it's generated by CMS. The brains of the view are in another view rendered by RenderAction.
Up until now it has looked like this:
Main.cshtml
<div>CMS content</div>
#{
var myContent = new MainContentModel() {
SomethingUsedFurtherDown = "Easier for CMS people to edit"
}
Html.RenderAction("_Main", "Foo", new { arg1 = "this", arg2 = "that", content = myContent });
}
MainContentModel.cs
namespace MyApp.Services.ViewModels.Foo
{
public class MainContentModel
{
public string SomethingUsedFurtherDown { get; set; }
}
}
MainViewModel.cs
namespace MyApp.Services.ViewModels.Foo
{
public class MainViewModel
{
public string Arg1 { set; set; }
public string Arg2 { set; set; }
public string Name { get; set; }
public string Age { get; set; }
public string Address { get; set; }
public MainContentModel Content { get; set; }
}
}
_Main.cshtml
#model MyApp.Services.ViewModels.Foo.MainViewModel
#Html.EditorFor(m => m.Name)
#Html.EditorFor(m => m.Age)
#Html.EditorFor(m => m.Address)
<!-- whatever - doesn't matter -->
FooController.cs
namespace My.App.Controllers
{
using System;
using System.Web.Mvc;
public class FooController
{
public ActionResult Main(string arg1, string arg2, MainContentModel cm)
{
var vm = new MainViewModel() { Arg1 = arg1, Arg2 = arg2, Content = cm };
return this.View("_Main", vm);
}
}
}
All works fine. So why am I bothering you? Well, this isn't the real code, obviously. There are many more arguments to the controller method and it's all getting rather messy. So I figured I would pass in the view model from the outer view.
Main.cshtml
<div>CMS content</div>
#{
var myVM = new MainViewModel() {
Arg1 = "this"
, Arg2 = "that"
, Content = new MainContentModel() {
SomethingUsedFurtherDown = "Easier for CMS people to edit"
}
};
Html.RenderAction("_Main", "Foo", new { vm = myVM });
}
...and just have one argument to the controller method
FooController.cs
namespace My.App.Controllers
{
using System;
using System.Web.Mvc;
public class FooController
{
public ActionResult Main(MainViewModel vm)
{
return this.View("_Main", vm);
}
}
}
And that's where the trouble starts. I get this error:
The view '_Main' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Foo/_Main.aspx
~/Views/Foo/_Main.ascx
~/Views/Shared/_Main.aspx
~/Views/Shared/_Main.ascx
~/Views/Foo/_Main.cshtml
~/Views/Foo/_Main.vbhtml
~/Views/Shared/_Main.cshtml
~/Views/Shared/_Main.vbhtml
~/Views/CMS/_Main.cshtml
~/Views/CMS/Foo/_Main.cshtml
But if I remove the initialisation of the content model, it all works again. Well, okay, it doesn't work work. But the error goes away, leaving me to come up with the obvious solution of adding the content model to the argument list and assigning it to the view model in the controller method.
Main.cshtml
<div>CMS content</div>
#{
var myVM = new MainViewModel() {
Arg1 = "this"
, Arg2 = "that"
};
var myCm = new MainContentModel() {
SomethingUsedFurtherDown = "Easier for CMS people to edit"
};
Html.RenderAction("_Main", "Foo", new { vm = myVM, cm = myCm });
}
FooController.cs
namespace My.App.Controllers
{
using System;
using System.Web.Mvc;
public class FooController
{
public ActionResult Main(MainViewModel vm, MainContentModel cm)
{
vm.Content = cm;
return this.View("_Main", vm);
}
}
}
Which is fine except that there are quite a few child objects of the real view model and I don't want to separate those out into arguments - it defeats the purpose of what is supposed to be a tidying up exercise.
Question
Is MVC4 supposed to be binding the child objects seamlessly and this is a bug? Or does it just not work this way and my only choice is to separate them out into extra parameters as above?
Cheers,
.pd.
Just in case anybody else has fallen into this trap. The problem was not the model binding. MVC 4 binds nested objects just fine. I was missing the subtlety of the error. The standard here is to prefix the "real" view name with an underscore and it was this that was not being found. The failure was occurring here:
return this.View("_Main");
What I didn't include in my post (cuz if I'd remembered, that would've fixed it!) was the fact that in the real situation the RenderAction looks like this:
RenderAction("Main", "Foo", new { area = "SomeArea", ... });
And I had missed off the area in my refactoring. Pretty embarrassing but if it stops somebody else beating their head against the wall then the shame will have been worth it :-)

How to render the checkbox in editor window with corresponding boolean value(i.e)checked or unchecked in MVC 4..?

Model:
public partial class TBLAppUser
{
public bool isActive { get; set; }
}
View:
#Html.CheckBoxFor(u => u.useredit.isActive)
you initialize an instance of TBLAppUser, set the IsActive of that instance to true, and pass that instance to the view. This is quite a simple situation. I think you better look at introductory tutorials found in here asp.net/mvc/overview/getting-started .
following is how your controller action would look like
[HttpGet]
public ActionResult Index()
{
var mainModel = //what ever the model you represent by u in the view
mainModel.useredit = new TBLAppUser{ isActive = true};
return View(mainModel);
}

How to upload related entities via MVC4 upshot

I get a simple DTO entity A loaded into my upshot viewmodel which is happily viewable via Knockoutjs.
My DTO A contains a List entities. So I can foreach over the elements inside A.
again:
class A
{
someprop;
List<B> childB;
}
Class B
{
somepropB;
}
So far so good. I can iterated over the data with no problem.
But if I change "someprop" inside an instance of A and SaveAll the server will not respond at all.
The updateData controlle method is not even invoked.
If I clear the childB.Clear() before transmitting it to the client, all is fine.
It seems the upshot is not able to update entities with collections?
There is a bit of work to do if you want such a scenario to work. Upshot only turns the parent entities in observable items. So only the javascript representation of class A is a knockout observable, the javascript representation of class B is not. Therefore Upshot is not aware of any changes in associated objects.
The solution is to map the entities manually. To make my life easier, I've used code from my 'DeliveryTracker' sample application in the code snippets below. In my blog article you can see an example of manual mapping: http://bartjolling.blogspot.com/2012/04/building-single-page-apps-with-aspnet.html so my examples below are working on the 'delivery' and 'customer' objects.
The server-side domain model
namespace StackOverflow.q9888839.UploadRelatedEntities.Models
{
public class Customer
{
[Key]
public int CustomerId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public virtual ICollection<Delivery> Deliveries { get; set; }
}
public class Delivery
{
[Key]
public int DeliveryId { get; set; }
public string Description { get; set; }
public bool IsDelivered { get; set; }
[IgnoreDataMember] //needed to break cyclic reference
public virtual Customer Customer { get; set; }
public virtual int CustomerId { get; set; }
}
public class AppDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<Delivery> Deliveries { get; set; }
}
}
The data service controller
The data service controller exposes the data conforming to OData standards on
"http://localhost:[yourport]/api/dataservice/GetCustomers". In order to be able to update both customers and deliveries you need to define an UpdateCustomer AND UpdateDelivery function
namespace StackOverflow.q9888839.UploadRelatedEntities.Controllers
{
public class DataServiceController : DbDataController<AppDbContext>
{
//Service interface for Customer
public IQueryable<Customer> GetCustomers()
{
return DbContext.Customers.Include("Deliveries").OrderBy(x => x.CustomerId);
}
public void InsertCustomer(Customer customer) { InsertEntity(customer); }
public void UpdateCustomer(Customer customer) { UpdateEntity(customer); }
public void DeleteCustomer(Customer customer) { DeleteEntity(customer); }
//Service interface for Deliveries
public void InsertDelivery(Delivery delivery) { InsertEntity(delivery); }
public void UpdateDelivery(Delivery delivery) { UpdateEntity(delivery); }
public void DeleteDelivery(Delivery delivery) { DeleteEntity(delivery); }
}
}
Client-side domain model
Add a new javascript file containing your client-side model. Here I'm explicitly turning every property into an knockout observable. The key for solving your problem is the line inside the constructor of the Customer object where I'm mapping the incoming deliveries into an observable array
/// <reference path="_references.js" />
(function (window, undefined) {
var deliveryTracker = window["deliveryTracker"] = {}; //clear namespace
deliveryTracker.DeliveriesViewModel = function () {
// Private
var self = this;
self.dataSource = upshot.dataSources.Customers;
self.dataSource.refresh();
self.customers = self.dataSource.getEntities();
};
deliveryTracker.Customer = function (data) {
var self = this;
self.CustomerId = ko.observable(data.CustomerId);
self.Name = ko.observable(data.Name);
self.Address = ko.observable(data.Address);
self.Latitude = ko.observable(data.Latitude);
self.Longitude = ko.observable(data.Longitude);
self.Deliveries = ko.observableArray(ko.utils.arrayMap(data.Deliveries, function (item) {
return new deliveryTracker.Delivery(item);
}));
upshot.addEntityProperties(self, "Customer:#StackOverflow.q9888839.UploadRelatedEntities.Models");
};
deliveryTracker.Delivery = function (data) {
var self = this;
self.DeliveryId = ko.observable(data.DeliveryId);
self.CustomerId = ko.observable(data.CustomerId);
self.Customer = ko.observable(data.Customer ? new deliveryTracker.Customer(data.Customer) : null);
self.Description = ko.observable(data.Description);
self.IsDelivered = ko.observable(data.IsDelivered);
upshot.addEntityProperties(self, "Delivery:#StackOverflow.q9888839.UploadRelatedEntities.Models");
};
//Expose deliveryTracker to global
window["deliveryTracker"] = deliveryTracker;
})(window);
The View
In the index.cshtml you initialize Upshot, specify custom client mapping and bind the viewmodel
#(Html.UpshotContext(bufferChanges: false)
.DataSource<StackOverflow.q9888839.UploadRelatedEntities.Controllers.DataServiceController>(x => x.GetCustomers())
.ClientMapping<StackOverflow.q9888839.UploadRelatedEntities.Models.Customer>("deliveryTracker.Customer")
.ClientMapping<StackOverflow.q9888839.UploadRelatedEntities.Models.Delivery>("deliveryTracker.Delivery")
)
<script type="text/javascript">
$(function () {
var model = new deliveryTracker.DeliveriesViewModel();
ko.applyBindings(model);
});
</script>
<section>
<h3>Customers</h3>
<ol data-bind="foreach: customers">
<input data-bind="value: Name" />
<ol data-bind="foreach: Deliveries">
<li>
<input type="checkbox" data-bind="checked: IsDelivered" >
<span data-bind="text: Description" />
</input>
</li>
</ol>
</ol>
</section>
The Results
When navigating to the index page, the list of customers and related deliveries will be loaded asynchronously. All the deliveries are grouped by customer and are pre-fixed with a checkbox that is bound to the 'IsDelivered' property of a delivery. The customer's name is editable too since it's bound to an INPUT element
I don't have enough reputation to post a screenshot so you will have to do without one
When checking or unchecking the IsDelivered checkbox now, Upshot will detect the change and post it to the DataService Controller
[{"Id":"0",
"Operation":2,
"Entity":{
"__type":"Delivery:#StackOverflow.q9888839.UploadRelatedEntities.Models",
"CustomerId":1,
"DeliveryId":1,
"Description":"NanoCircuit Analyzer",
"IsDelivered":true
},
"OriginalEntity":{
"__type":"Delivery:#StackOverflow.q9888839.UploadRelatedEntities.Models",
"CustomerId":1,
"DeliveryId":1,
"Description":"NanoCircuit Analyzer",
"IsDelivered":false
}
}]
When modifying the customer's name, Upshot will submit the changes when the input box loses focus
[{
"Id": "0",
"Operation": 2,
"Entity": {
"__type": "Customer:#StackOverflow.q9888839.UploadRelatedEntities.Models",
"Address": "Address 2",
"CustomerId": 2,
"Latitude": 51.229248,
"Longitude": 4.404831,
"Name": "Richie Rich"
},
"OriginalEntity": {
"__type": "Customer:#StackOverflow.q9888839.UploadRelatedEntities.Models",
"Address": "Address 2",
"CustomerId": 2,
"Latitude": 51.229248,
"Longitude": 4.404831,
"Name": "Rich Feynmann"
}
}]
So if you follow above procedure, Upshot will both update parent and child entities for you.