One again Microsoft poor documentation has left me confused. I am trying to use the new features of the .NET 4.0 framework. I am using the following code to populate the Title and Director but it keeps getting blank.
The service returns the result correctly like
[d: { title = "ss, director ="" } something like that but the li never gets populated.
<script language="javascript" type="text/javascript">
Sys.require([Sys.components.dataView, Sys.components.dataContext,Sys.scripts.WebServices], function () {
Sys.create.dataView("#moviesView",
{
dataProvider: "MovieService.svc",
fetchOperation: "GetMovies",
autoFetch: true
});
});
</script>
And here it the HTML code:
<ul id="moviesView">
<li>
{{Title}} - {{Director}}
</li>
</ul>
IS THIS THE LATEST URL TO Start.js file.
<script src="http://ajax.microsoft.com/ajax/beta/0911/Start.js"></script>
Here is the Ajax-Enabled WCF Service:
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MovieService
{
[OperationContract]
public Movie GetMovies()
{
return new Movie() { Title = "SS", Director = "SSSSS" };
}
}
[DataContract]
public class Movie
{
[DataMember]
public string Title { get; set; }
[DataMember]
public string Director { get; set; }
}
You need to add the sys-template class attribute to the unordered list tag.
<ul id="moviesView" class="sys-template">
Here's an excerpt from Client-side Data Binding in ASP.NET AJAX 4.0
The one other requirement for defining
a template is the parent element must
have the sys-template CSS class
applied, and that class must be
defined with display set to none, as
shown in the example above. This
convention serves two purposes – it
helps the parser identify which
elements are part of a template on
your page (which will become important
when we use declarative
instantiation), and it keeps the
template markup hidden until ASP.NET
Ajax has completed the binding (it
will toggle the display to be
visible).
Related
i am newbie knockout.js. Also i ama upper intermadiate in asp.net mvc 3. i really want to learn how to use knockout js in mvc 3 razor? but below code is not working also return to me empty total price. There is no error. Help please thanks...
Model:
public class GiftModel
{
public string Title { get; set; }
public double Price { get; set; }
}
View:
#using System.Web.Script.Serialization;
#model IEnumerable<knockout1.Models.GiftModel>
#{
ViewBag.Title = "Index";
}
<script src="/Scripts/knockout-2.1.0.js" type="text/javascript"></script>
<script type="text/javascript">
var initialData = #(new JavaScriptSerializer().Serialize(Model));
var viewModel = {
gifts : ko.observableArray(initialData)
};
ko.applyBindings(viewModel);
</script>
<h2>Index</h2>
<p>You have asked for <span data-bind="text: gifts().length"> </span> gift(s)</p>
Controller:
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
var initialState = new[] {
new GiftModel { Title = "Tall Hat", Price = 49.95 },
new GiftModel { Title = "Long Cloak", Price = 78.25 }
};
return View(initialState);
}
}
I guess you are following this tutorial.
You have a couple of errors. First replace:
var initialData = #(new JavaScriptSerializer().Serialize(Model));
with:
var initialData = #Html.Raw(Json.Encode(Model));
This ensures that your model is properly JSON encoded. In the original article Steven Sanderson is using the WebForms view engine but you seem to be using the Razor view engine. So make sure that you adapt your syntax accordingly (don't forget that the # razor function automatically html encodes the output contrary to the <%= WebForms syntax).
And the second problem with your code is that you attempted to bind your knockout model before your DOM is ready (i.e. you have placed the ko.applyBindings(viewModel); call before the actual span containing the bindings). So either wrap your call in a $(document).ready or place your scripts at the end of the document, just before closing your </body> tag (recommended).
Also I would recommend you using url helpers to reference your scripts, don't just hardcode those urls, your application will break as soon as you publish in IIS:
#model IEnumerable<GiftModel>
<h2>Index</h2>
<p>You have asked for <span data-bind="text: gifts().length"> </span> gift(s)</p>
<script src="#Url.Content("~/Scripts/knockout-2.1.0.js")" type="text/javascript"></script>
<script type="text/javascript">
var initialData = #Html.Raw(Json.Encode(Model));
var viewModel = {
gifts : ko.observableArray(initialData)
};
ko.applyBindings(viewModel);
</script>
So as you can see the 2 problems you were having have strictly nothing to do with knockoutjs. So what I would recommend you if you want to learn some framework is to learn it independently. Don't mix up technologies or you will get mixed up.
So go ahead over the knockoutjs site and start the tutorials working on static HTML pages. Forget about ASP.NET MVC for the moment. Forget about Entity Framework. Just learn the framework starting from a static HTML page. This way you will better understand how it works.
I'm using editor from Kendo UI, so I have big problem.
I don't know how display items which are returned by editor.
Editor convert something like:
<img src="someurl" />
to:
lt;p><img src="someurl"/></p>
and I keep converted string in database, and try display it with:
#Html.Raw(item.description)
where description is string returned by kendo.
So I have no idea how display it correctly in my View
Any help would be appreciated.
There is an option of the KendeUI editor called encoded which configures whether the Editor should submit encoded HTML tags or not.
The default value for encoded is true
If you wan't to store the unencoded text use this sniplet when creating your editor:
$("#Editor").kendoEditor({
encoded: false
});
But because you are not sending encoded text to the server the Asp.net request validator kicks in and it will abort your request.
If you are using strongly typed views what you can do is to use the AllowHtmlAttribute on your model property:
View:
#model MyModel
#using(Html.BeginForm("SomeAction", "SomeController"))
{
#Html.TextAreaFor(m => m.Editor)
<input type="submit" value="Save" />
}
<script type="text/javascript">
$(function(){
$("#Editor").kendoEditor({
encoded: false
});
});
</script>
Model:
public class MyModel
{
[AllowHtml]
public string Editor { get; set; }
}
Controller action
public ActionResult SomeAction(MyModel myModel)
{
//Save to db, etc.
}
You also need to set the following in your web.config or this attribute won't have effect in .NET 4.0:
<httpRuntime requestValidationMode="2.0"/>
I found this solution for MVC:
in View
<div class="editor-field">
#(Html.Kendo().EditorFor(model => model.HtmlField).Encode(false))
#Html.ValidationMessageFor(model => model.HtmlField)
</div>
in model:
[DataType(DataType.Html)]
[AllowHtml]
public string HtmlField{ get; set; }
That was enough
Simplier way to do it is make changes in controller, no in view and model. So:
View
$("#Editor").kendoEditor();
Model
public class MyModel
{
public string Editor { get; set; }
}
Controller
Editor = Server.HtmlDecode(Editor);
HtmlDecode
The editor templates generated from the .NET Wrappers aren't working any more. Here is a fix.
http://pknopf.com/blog/kendo-ui-editor-templates-for-asp-net
I am creating a breadcrumb partial view which takes in a collection of title/URL. The collection will be generated in action methods and would have to be available on the breadcrumb partial view.
I tried couple of ways to get it done and this is one among such: http://goo.gl/rMFlp
But some how i could not get it working. All i get is an "Object reference not set to an instance of an object." Can you guys help me out?
{Updare}
Here is the code:
I created a Model class as follows
public class ShopModel
{
public Dictionary<string,string> Breadcrumb { get; set; }
}
Action Method
public ActionResult Index()
{
var breadcrumbCollection = new Dictionary<string,string>();
breadcrumbCollection.Add("/home","Home");
breadcrumbCollection.Add("/shop","Shop");
var model = new ShopModel() { Breadcrumb = breadcrumbCollection};
return View(model);
}
Model binding the view - Index
#Model NexCart.Model.Model.Custom.ShopModel
Finally here is the code on partial view:
<div>
#{
foreach (var item in #Model.Breadcrumb)
{
#item.Key
}
}
You haven't shown any code, so your question is impossible to answer. This being said here's how you could proceed. As always in an ASP.NET MVC application you start by defining a view model:
public class Breadcrumb
{
public string Title { get; set; }
public string Url { get; set; }
}
then you could write a controller action which will populate a collection of breadcrumbs and pass them to a partial view:
public class BreadcrumbController: Controller
{
public ActionResult Index()
{
// TODO: pull the breadcrumbs from somewhere instead of hardcoding them
var model = new[]
{
new Breadcrumb { Title = "Google", Url = "http://www.google.com/" },
new Breadcrumb { Title = "Yahoo", Url = "http://www.yahoo.com/" },
new Breadcrumb { Title = "Bing", Url = "http://www.bing.com/" },
};
return PartialView(model);
}
}
then you could have a corresponding partial view which will render this model (~/Views/Breadcrumb/Index.cshtml):
#model IEnumerable<Breadcrumb>
<ul>
#Html.DisplayForModel()
</ul>
and the corresponding display template (~/Views/Breadcrumb/DisplayTemplates/Breadcrumb.cshtml):
#model Breadcrumb
<li>
#Model.Title
</li>
Now all that's left is to include this child action somewhere using the Html.Action helper. For example you could do this in the _Layout if this breadcrumb is repeated on each page:
#Html.Action("Index", "Breadcrumb")
But obviously it could also be done in any view.
I have the following view model
public class FooViewModel
{
public int SelectedCategoryId { get; set; }
public IEnumerable<CategoryDto> AvailableCategories { get; set; }
}
in my view I am using jquery template to bind my data to a select tag
<script type="text/javascript">
$(document).ready(function () {
var categories = #Model.AvailableCategories.ToJson();
var categoryMarkup = '<option value="${Id}"${Selected}>${Name}</option>';
$.template("categoryTemplate", categoryMarkup);
$.tmpl("categoryTemplate", categories).appendTo($('#categories'));
});
</script>
<select id="categories"></select>
What would I need to do to make sure my SelectedCategoryId viewmodel property gets populated on the POST? I'd prefer not to use the Html.DropDownList if I can get away with it
Simply add it in your form using the html helpers. Ex.
Html.HiddenFor(o=>o.SelectCategoryId)
If your combo box is changing this then simply set an onchange event
("#selectId").change(function(){
//something like this - untested
$("#SelectCategoryId").val(this.value);
});
Unless you are using an explicit jQuery .ajax() call in that case you will need to add this value to the data. Which are you using when you post? I don't see your form above anywhere
I am becoming more familiar with MVC 3 and the RAZOR view engine. I have a question regarding layouts and shared controls on pages.
Let’s say I have a header section defined in my main layout. In that header is a dropdown I need to populate with project names. This dropdown will serve as a context for the entire site and is present on all pages. As an example, if the user selects “Project A” from the drop down, all of the views for the site will be based on “Project A”. Since this dropdown control is rather static and is used by the entire site, where is the best place to put the code to pull all the projects to display in the dropdown? In a Partial View? In a HTML helper? Another thought is, if a user selects a new value, they would be taken to a dashboard or similar page for that newly selected project. I am trying to figure out how to reuse this control on every page in the site without having to keep wiring it up in every possible controller.
You could use a child action along with the Html.Action helper. So you start by defining a view model:
public class ProjectViewModel
{
[DisplayName("Project name")]
public string ProjectId { get; set; }
public IEnumerable<SelectListItem> ProjectNames { get; set; }
}
then a controller:
public class ProjectsController: Controller
{
private readonly IProjectsRepository _repository;
public ProjectsController(IProjectsRepository repository)
{
_repository = repository;
}
public ActionResult Index(string projectId)
{
var projects = _repository.GetProjects();
var model = new ProjectViewModel
{
ProjectId = projectId,
ProjectNames = projects.Select(x => new SelectListItem
{
Value = x.Id,
Text = x.Name
})
};
return PartialView(model);
}
}
then the corresponding view (~/views/projects/index.cshtml):
#model ProjectViewModel
#Html.LabelFor(x => x.ProjectId)
#Html.DropDownListFor(
x => x.ProjectId,
Model.ProjectNames,
new {
id = "projects",
data_url = Url.Action("SomeAction", "SomeController")
}
)
Now all that's left is to render this widget inside the _Layout.cshtml:
#Html.Action("Index", "Products", new { projectid = Request["projectId"] })
And now we could put some javascript so that when the user decides to change the selection he is redirected to some other action:
$(function() {
$('#projects').change(function() {
var url = $(this).data('url');
var projectId = encodeURIComponent($(this).val());
window.location.href = url + '?projectid=' + projectId;
});
});
Another possibility is to put the dropdown inside an HTML form:
#model ProjectViewModel
#using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Get))
{
#Html.LabelFor(x => x.ProjectId)
#Html.DropDownListFor(
x => x.ProjectId,
Model.ProjectNames,
new {
id = "projects",
}
)
}
so that inside the javascript we don't have to worry about building urls when the selection changes and simply trigger the containing form submission:
$(function() {
$('#projects').change(function() {
$(this).closest('form').submit();
});
});
We just did a similiar thing on a project.
First, you can't really put it in a section because you have to put that section on every view, you could put it in a partial but you would still have to call it from every view.
Second, you can't really put it in the Layout page because the layout page isn't passed any kind of model. So I created an html helper and referenced that in the layout page. There are lots of tutorials on creating html helpers so I won't put the code here. But essentially in your html helper you can make a database call to get all of your projects. Then you can create a select list using string builder in the html helper and return that to the layout page. We then used jquery to add an on change event to the select list. When the select list changed it loaded a new page. So for example, in your select list the value of each item could be the project id, then on change it redirects them to a page like /Projects/View?id=234 where 234 is your project id.
So things to research. 1. Creating HTML Helpers 2. JQUERY change event.
That should get you in the right direction. Let me know if you need any other help and I can post some code.