Creating a KnockoutJS Model From an ASP.NET MVC complex model - c#

I would like to create knockout viewModel from asp.net MVC model using ko.mapping.fromJS() method but my form didn't populating values.
In view I created script looks like that:
<script type="text/javascript">
var tmp = #Html.Raw(Model.ToJson());
var viewModel = ko.mapping.fromJS(tmp);
ko.applyBindings(viewModel);
</script>
#Html.Raw(Model.ToJson() returns value
{"id":1,
"surveyCode":null,
"title":"Życie",
"description":"Ankieta, w której zadawane będą pytania na temat codziennego życia ",
"dateStart":"2013-12-12T00:00:00",
"dateEnd":"2014-12-30T00:00:00",
"createDate":"2014-01-07T03:23:16.053",
"lastModification":"2014-01-07T03:23:16.053",
"isActive":false,
"questions":[{"id":1,
"surveyID":1,
"content":"Co jesz na śniadanie?",
"tips":"wybierz jedną odpowiedź",
"questionType":1,
"isRequired":true,
"answers": [{"id":1,
"questionID":1,
"answerContent":"Jajecznicę",
"isOpenAnswer":false},
{"id":2,
"questionID":1,
"answerContent":"Kiełbaski",
"isOpenAnswer":false},
{"id":3,
"questionID":1,
"answerContent":"Płatki na mleku",
"isOpenAnswer":false},
{"id":4,
"questionID":1,
"answerContent":"Inne",
"isOpenAnswer":true}]},
{"id":2,
"surveyID":1,
"content":"Czym się zajmujesz w życiu?",
"tips":"napisz krótką historię",
"questionType":3,
"isRequired":true,
"answers":[]}]}
but when I want to bind 'title' property to <span> <span data-bind="text:title"></span> it is not working. When I run my app in firefox and turn on firebug script console and set breakpiont to line var tmp = #Html.Raw(Model.ToJson()); returns correct value, press F10 going to next line var viewModel = ko.mapping.fromJS(tmp); and finally press F10 and nothing happen, script not execute next line ko.applyBindings(viewModel);.
And it is my question. Is it possible to mapp my mvc model using knockout mapping plugin automacly? or maybe should I do some manualy staf to map mvc model to knockout viewModel.
I'm looking for answers on this sites:
link1
and
stackowerflow
but maybe I didn't understand this posts.
Edit
my view looks like this:
#using Inżynierka.Extensions
#model Inżynierka.Models.Survey
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>SurveyAnswer</h4>
<hr />
#Html.ValidationSummary(true)
Title: <span data-bind="text:title"></span>
</div>
}
#section Scripts {
<script src="../../Scripts/jQuery.tmpl.min.js" type="text/javascript"></script>
<script src="../../Scripts/knockout-3.0.0.js" type="text/javascript"></script>
<script src="../../Scripts/knockout.validation.js"></script>
<script src="../../Scripts/knockout.knockout.mapping-latest.js"></script>
<script type="text/javascript">
var tmp = #Html.Raw(Model.ToJson());
var viewModel = ko.mapping.fromJS(tmp);
ko.applyBindings(viewModel);
</script>
#Scripts.Render("~/bundles/jqueryval")
}
Edit 2
It is html sourse of my page:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.0.0.js'></script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create</title>
<link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>
<script src="/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Ankietyy</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>Moje Ankiety</li>
<li>Strona Główna</li>
<li>O Projekcie</li>
<li>Kontakt</li>
</ul>
<form action="/Account/LogOff" class="navbar-right" id="logoutForm" method="post"><input name="__RequestVerificationToken" type="hidden" value="fWDZFmyGqJyU3ATUf2IbHDdkbo22bzObUMwUfxfqwXIiqGvRYzMhApWS3I5GkkHnZD7ieDxLfh84s2-prLDtSGeE6_D7p7cT-fmQBszeM06p-fZ7RzhOPn0P8EDftLRwT8YQA8t2U56dlLX_lx3G4Q2" /> <ul class="nav navbar-nav navbar-right">
<li>
Witaj Bartek!
</li>
<li>Wyloguj się</li>
</ul>
</form>
</div>
</div>
</div>
<div class="container body-content">
<form action="/SurveyAnswer/CompleteSurvey/1" method="post"><input name="__RequestVerificationToken" type="hidden" value="KOALGZbw0WhFlBV4LHx530Oen59aBWF62b6s58GIUikx3A62uhcAi3-74auJpLtI4fYj9kmcPjlgNu1TeuNrYukpFlll1cGCOIcjjewtFou4M9C3_bHDFk7UoZk_tKpw7SxcXa3UbgwIj4ZhCRM6_g2" /> <div class="form-horizontal">
<h4>SurveyAnswer</h4>
<hr />
Title: <span data-bind="text:title"></span>
</div>
</form><script type="text/javascript">
var tmp = {"id":1,"surveyCode":null,"title":"Życie","description":"Ankieta, w której zadawane będą pytania na temat codziennego życia ","dateStart":"2013-12-12T00:00:00","dateEnd":"2014-12-30T00:00:00","createDate":"2014-01-07T03:23:16.053","lastModification":"2014-01-07T03:23:16.053","isActive":false,"questions":[{"id":1,"surveyID":1,"content":"Co jesz na śniadanie?","tips":"wybierz jedną odpowiedź","questionType":1,"isRequired":true,"answers":[{"id":1,"questionID":1,"answerContent":"Jajecznicę","isOpenAnswer":false},{"id":2,"questionID":1,"answerContent":"Kiełbaski","isOpenAnswer":false},{"id":3,"questionID":1,"answerContent":"Płatki na mleku","isOpenAnswer":false},{"id":4,"questionID":1,"answerContent":"Inne","isOpenAnswer":true}]},{"id":2,"surveyID":1,"content":"Czym się zajmujesz w życiu?","tips":"napisz krótką historię","questionType":3,"isRequired":true,"answers":[]},{"id":14,"surveyID":1,"content":"Pytanie końcowe","tips":"napisz","questionType":1,"isRequired":true,"answers":[{"id":9,"questionID":14,"answerContent":"test","isOpenAnswer":false},{"id":10,"questionID":14,"answerContent":"test2","isOpenAnswer":false},{"id":11,"questionID":14,"answerContent":"test3","isOpenAnswer":false}]}],"surveyAnswers":[],"codeForUsers":[]};
var viewModel = ko.mapping.fromJS(tmp);
ko.applyBindings(viewModel);
</script>
<hr />
<footer>
<p>© 2014 - My ASP.NET Application</p>
</footer>
</div>
<script src="/Scripts/jquery-2.0.3.js"></script>
<script src="/Scripts/bootstrap.js"></script>
<script src="/Scripts/respond.js"></script>
<script src="../../Scripts/jQuery.tmpl.min.js" type="text/javascript"></script>
<script src="../../Scripts/knockout-3.0.0.js" type="text/javascript"></script>
<script src="../../Scripts/knockout.validation.js"></script>
<script src="../../Scripts/knockout.mapping-latest.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
{"appName":"Firefox","requestId":"9f8e517696004299808eb3caccb0e136"}
</script>
<script type="text/javascript" src="http://localhost:11897/dc47e85290da49019e6425ddd16f962a/browserLink" async="async"></script>
<!-- End Browser Link -->
</body>
</html>
Answer for my issue
View should looks like that:
#using Inżynierka.Extensions
#model Inżynierka.Models.Survey
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>SurveyAnswer</h4>
<hr />
#Html.ValidationSummary(true)
Title: <span data-bind="text:title"></span>
</div>
}
#section Scripts {
<script src="../../Scripts/knockout-3.0.0.js" type="text/javascript"></script>
<script src="../../Scripts/knockout.mapping-latest.js"></script>
<script type="text/javascript">
var tmp = #Html.Raw(Model.ToJson());
var viewModel = ko.mapping.fromJS(tmp);
ko.applyBindings(viewModel);
</script>
#Scripts.Render("~/bundles/jqueryval")
}
Thanks everyone for replies, specially for #VolodymyrBilyachat whose advices were most relevant.

Well after you post source, then other idea what it could is that some scripts are conflicting, try to remove scripts and left only knockout ones

Wrap your knockout view model in a document.ready function
<script type="text/javascript">
$document.ready(function() {
var tmp = #Html.Raw(Model.ToJson());
var viewModel = ko.mapping.fromJS(tmp);
ko.applyBindings(viewModel);});
</script>
Also note that your viewModel isn't a true view model at that point so consider using a view model that contains the ko.observable property 'myData' or something to hold your data and then applying bindings

For complex models I don't believe mappings and simply, I'm parsing json on my own and populate model via loops, ifs and so on. I think, this isn't the worst solution, because debugging and fixing data becomes simplier.

Related

Materialize CSS examples are not working in Blazor WASM

I'm trying to use the materialize framework for css with a Blazor application, however, when I copy/paste some of the examples into a layout, component, etc I don't get what Materialize shows on the example. There aren't any CSS/JS loading or console errors that can be identified in dev tools, but it seems like something isn't loading because lots of components aren't working as the examples show.
For example, the tab indicator that apperas under the active tab and hops from tab to tab when you select one.
layout page:
#inherits LayoutComponentBase
<div class="main">
<nav class="nav-extended">
<div class="nav-wrapper">
Logo
<i class="material-icons">menu</i>
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li>Sass</li>
<li>Components</li>
<li>JavaScript</li>
</ul>
</div>
<div class="nav-content">
<ul class="tabs tabs-transparent">
<li class="tab">Test 1</li>
<li class="tab"><a class="" href="#test2">Test 2</a></li>
<li class="tab disabled">Disabled Tab</li>
<li class="tab">Test 4</li>
</ul>
</div>
</nav>
<div class="content px-4">
#Body
</div>
</div>
Edit
Looks like the M.AutoInit() isn't firing properly. Can someone point out where the best place to call that function would be? I tried a
document.onload = M.AutoInit();
on the index.html page and a interop JS on my component
#code {
...
protected override void OnInitialized()
{
JSRuntime.Invoke<string>("M.AutoInit");
}
...
}
Neither worked but maybe I'm doing the JSInterop wrong, couldn't find a definitive example, similar to what I'm trying to do, in the docs. Any suggestions or pointers would be great!
This works for me(very important respect the async await, so if you have any errors the Exception is properlly thowed to your browser console)
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("M.AutoInit");
}
}
In the static JavaScript file that is used to initialize materialize elements, add AutoInit method to load first on DOMContentLoaded event listener.
Consider this example that initializes Materialize Sidenav:
In the Sidenav.razor:
<nav> <!-- navbar content here -optional --> </nav>
<ul id="slide-out" class="sidenav">
<li>
<div class="user-view">
<div class="background">
<img width="300" src="office.jpg">
</div>
<a href="#user">
<img class="circle" width="50"
src="user_female.svg.png">
</a>
<span class="white-text name">John Doe</span>
<span class="white-text email">xyz#xyz.com</span>
</div>
</li>
<li><i class="material-icons">cloud</i>First Link With Icon</li>
<li>Second Link</li>
<li><div class="divider"></div></li>
<li><a class="subheader">Sub-header</a></li>
<li><a class="waves-effect" href="#!">Third Link With Waves</a></li>
</ul>
<i class="material-icons">menu</i>
In the main.js:
(function () {
"use strict";
var M = window.M || globalThis.M;
function activateSideNav() {
var elems = document.querySelectorAll('.sidenav');
var options = {};
M.Sidenav.init(elems, options);
}
document.addEventListener('DOMContentLoaded', function () {
M.AutoInit();
setTimeout(activateSideNav, 864);
});
})();
In the MainLayout.razor:
<Sidenav />
<div class="row">
<div class="col s12 m12 l12 xl12">
#Body
</div>
</div>
Also make sure that Materialize libraries are referenced properly in the _Host.cshtml
#page "/"
#namespace Example.Pages
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Example</title>
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
<base href="~/" />
<link href="css/materialize/css/materialize.css" rel="stylesheet" />
<link href="css/main.css" rel="stylesheet" />
</head>
<body>
<component type="typeof(App)" render-mode="ServerPrerendered" />
<script src="_framework/blazor.server.js"></script>
<script src="css/materialize/js/materialize.js"></script>
<script src="js/main.js"></script>
</body>
</html>

Bootstrap DateTimePicker not showing calendar when clicked

recently I tried to use Bootstrap DateTimePicker in my ASP.NET MVC project, and the calendar just wont show up. I believe I already put the Scripts and CSS in the right order.
Here is my CSS and Scripts :
<link href="~/Content/css/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.4.1.min.js" type="text/javascript"></script>
<script src="~/Scripts/moment.min.js" type="text/javascript"></script>
<script src="~/Scripts/bootstrap.min.js" type="text/javascript"></script>
<script src="~/Scripts/bootstrap-datetimepicker.min.js" type="text/javascript"></script>
#RenderSection("Scripts", required: false)
And this is my View Page :
<div class="col-md-3">
<div class="form-group">
<label>Tanggal Survey </label>
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
#section Scripts{
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker({
format: 'DD MMMM YYYY'
});
});
</script>
}
And when I click the input, it just show the date and never show the pop-up calendar,
here is the example
Check the examples here: minimum setup
For your datepicked to open with clicking on the input you need to remove the glyph and go with the minimum setup.
<div class="container">
<div class="row">
<div class='col-sm-6'>
<input type='text' class="form-control" id='datetimepicker4' />
</div>
<script type="text/javascript">
$(function () {
$('#datetimepicker4').datetimepicker();
});
</script>
</div>
</div>
Otherwise you can do this:
$(function() {
$('.datetimepicker').datetimepicker();
$('.datetimepicker-addon').on('click', function() {
$(this).prev('input.datetimepicker').data('DateTimePicker').toggle();
});
});

button not disabling after click

I am using this post to disable my buttons on click:
Prevent multiple form submits in MVC 3 with validation
This is my page source after it is rendered:
<!DOCTYPE html>
<html>
<head>
<title>Do not bookmark this page.</title>
<link href="/Content/reset.css" rel="stylesheet" type="text/css" />
<link href="/Content/Site.css" rel="stylesheet" type="text/css" />
<link href="/Content/styer.css?t=335" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="/Scripts/Views/main.js" type="text/javascript"></script>
<link rel="shortcut icon" href="/Content/favicon.ico" type="image/ico" />
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<script language="javascript" type="text/javascript">
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$('input[type="submit"]').attr('disabled', 'disabled');
}
});
});
</script>
</head>
<body>
<div class="page">
<div id="header">
<div id="headerimg"></div>
<div id="logindisplay">
[ Log On ]
</div>
<div id="menucontainer">
<ul id="menu">
<li>Home</li>
<li>Logon</li>
<li>Register</li>
<li>Contact Us</li>
<li>News</li>
</ul>
</div>
<div id="main">
<h2>Forgot Username</h2>
<p>
Please provide the email address on your web account. Once validated, your username will be sent to your email address for your records.
</p>
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<form action="/Account/ForgotUsername" method="post"> <div>
<fieldset>
<legend>Email address</legend>
<div class="editor-label">
<label for="EmailAddress">Email</label>
</div>
<div class="editor-field focus">
<input class="GenericTextBox" data-val="true" data-val-length="The Email must be at least 7 characters long." data-val-length-max="100" data-val-length-min="7" id="EmailAddress" name="EmailAddress" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="EmailAddress" data-valmsg-replace="true"></span>
</div>
<p>
<input id="btn" class="makePaymentInput" type="submit" value="Submit"/>
</p>
</fieldset>
</div>
</form>
<div style="clear: both;"></div>
</div>
<div id="footer">
</div>
</div>
</div>
<!-- Start of StatCounter Code for Default Guide -->
<script type="text/javascript">
var sc_project = 9150358;
var sc_invisible = 1;
var sc_security = "1af31df9";
var scJsHost = (("https:" == document.location.protocol) ? "https://secure." : "http://www.");
document.write("<sc" + "ript type='text/javascript' src='" + scJsHost + "statcounter.com/counter/counter.js'></" + "script>");
</script>
<noscript>
<div class="statcounter"><a title="web analytics" href="http://statcounter.com/" target="_blank"><img class="statcounter" src="http://c.statcounter.com/9150358/0/1af31df9/1/" alt="web analytics"></a></div>
</noscript>
<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
{"appName":"Internet Explorer"}
</script>
<script type="text/javascript" src="http://localhost:25759/610299fe88d74cee8d0267b4fc859da0/browserLink" async="async"></script>
<!-- End Browser Link -->
</body>
</html>
This works on most forms but this one, which is the main reason I used this code.
Anyone see why this one is not working?
Instead of writing this :-
$('input[type="submit"]').attr('disabled', 'disabled');
You should write this :-
$('input[type="submit"]').prop('disabled','true');

Beginner: Autocomplete not working?

I'm trying to create a autocomplete textbox.
This is what I have in view
#model .....
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using(Html.BeginForm("Action","Controller"))
{
#Html.TextBoxFor(m=>m.myEmail)
}
#section Scripts{
#Scripts.Render("~/Scripts/jquery-ui-1.10.4.min.js")
<script type="text/javascript">
$(function() {
$("#myEmail").
autocomplete({
source: '/App/Per',
minLength: 1,
}
);
});
</script>
}
When I type lets say s in textbox a request is sent to this method in controller
public JsonResult Person(string term)
{
var persons = FindPersons(term,"bk#hello.com","bk").ToArray();
var fullnameList = persons.Select(person => person.FirstName + " " + person.LastName).ToList();
return Json(fullnameList, JsonRequestBehavior.AllowGet);
}
in browser when I inspect the element in chrome and check the response i get the values, for example
0: "Person1"
1: "Person2"
2: "Person3"
3: "Person4"
Problem
My autocomplete box doesn't fill up with these data. Wasn't i supposed to get a listbox thingy at the bottom of the textbox with above names?
Edit 2: Generated HTML
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create - My ASP.NET Application</title>
<link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>
<script src="/Scripts/modernizr-2.7.1.js"></script>
</head>
<body>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Date Picker</a>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>Register</li>
<li>Log in</li>
</ul>
<div class="container body-content">
<link href="/Content/themes/base/minified/jquery-ui.min.css" rel="stylesheet"/>
<h2>Create</h2>
<form action="/App/Cr" method="post"><input id="myEmail" name="myEmail" type="text" value="" /></form>
</div>
<script src="/Scripts/jquery-2.0.3.js"></script>
<script src="/Scripts/bootstrap.js"></script>
<script src="/Scripts/respond.js"></script>
<script src="/Scripts/jquery-ui-1.10.4.min.js"></script>
<script type="text/javascript">
$(function() {
$("#myEmail").
autocomplete({
source: '/App/Per',
minLength: 1,
}
);
});
</script>
Nothing looks particularly off (aside from the CSS link being misplaced). You might want to try formatting your JSON a bit differently, which would also have the effect of answering your last question.
Instead of this:
public JsonResult Person(string term)
{
var persons = FindPersons(term,"bkc#example.com","bk").ToArray();
var fullnameList = persons.Select(person => person.FirstName + " " + person.LastName).ToList();
return Json(fullnameList, JsonRequestBehavior.AllowGet);
}
Try using:
public JsonResult Person(string term)
{
var persons = FindPersons(term,"bk#example.com","bk").ToArray();
return Json(persons.Select(p => new { label = p.FirstName + " " + p.LastName, value = p.Email }), JsonRequestBehavior.AllowGet);
}
This is one of the results the API says the widget will work with: http://api.jqueryui.com/autocomplete/#option-source

MVC4 with Telerik Editor not working

For some reason my Telerik MVC Editor() is not working. Can anyone spot what I´m doing wrong?
I´m using MVC4 with Razor view engine and Telerik version 2012.1.214
_Layout.cshtml includes this:
#using Smekklegt.Models
#using Telerik.Web.Mvc.UI
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="is" xml:lang="is">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.7.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.20.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/modernizr-2.5.3.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/AjaxLogin.js")" type="text/javascript"></script>
<meta name="viewport" content="width=device-width" />
<!-- Skrár frá template-->
<link href="#Url.Content("~/Content/rikona/styles/galleriffic.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/rikona/style.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Content/rikona/js/jquery-1.3.2.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/rikona/js/jquery.opacityrollover.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/rikona/js/jquery.galleriffic.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/rikona/js/gallery-settings.js")" type="text/javascript"></script>
<!--[if IE 6]>
<script src="../../Content/rikona/js/ie6-transparency.js"></script>
<script>
DD_belatedPNG.fix('#header .logo img, .subtitle img, .slideshow-container, .navigation-container #thumbs .thumbs li .thumb img, .navigation a.next, .footer-line, #sidebar .author-photo, .line, .commentlist .comment-reply-link, #contact-page #contact .submit');
</script>
<link rel="stylesheet" type="text/css" href="../../Content/rikona/styles/ie6.css" />
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="../../Content/rikona/styles/ie7.css" />
<![endif]-->
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="../../Content/rikona/styles/ie8.css" />
<![endif]-->
#(Html.Telerik().StyleSheetRegistrar()
.DefaultGroup(group => group
.Add("telerik.common.css")
.Add("telerik.simple.css")
.Combined(true)
.Compress(true))
)
</head>
<body>
<div id="wrap">
<div id="header">
<section id="login" style="float: right;">
#Html.Partial("_LogOnPartial")
</section>
<section style="float: left;">
<ul>
<li>#Html.ActionLink("Flokkar", "Index", "Category")</li>
<li>#Html.ActionLink("Vörur", "Index", "Product")</li>
</ul>
</section>
<div class="logo">
<img src="../../Content/rikona/images/smekklegt_banner2.jpg" alt="logo" width="400px;" />
</div>
<div id="nav">
<ul id="nav-pages">
<li>#Html.ActionLink("Forsíða", "Index", "Home")<span>|</span></li>
#foreach (Category category in (IEnumerable<Category>)ViewData["Categories"])
{
<li>#Html.ActionLink(category.Name, "FindProductsByCategory", "Product", new { catId = category.Id }, null)<span>|</span></li>
}
<li>#Html.ActionLink("smekklegt.is", "Contact", "Home")</li>
</ul>
</div>
</div>
<div id="frontpage-content">
<div id="container">
#RenderSection("featured", false)
<section class="content-wrapper main-content clear-fix">
#RenderBody()
</section>
</div>
</div>
<div id="footer" style="margin-top: 15px;">
<div class="footer-line">
</div>
<p>
© #DateTime.Now.Year Smekklegt ehf</p>
<div class="float-right">
<ul id="social">
<li>Facebook</li>
</ul>
</div>
</div>
#Html.Telerik().ScriptRegistrar().jQuery(false).DefaultGroup(g => g.Combined(true).Compress(true))
</div>
Create.cshtml includes this:
#using Telerik.Web.Mvc.UI
#model Smekklegt.Controllers.ProductFormViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Product</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Product.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Product.Name)
#Html.ValidationMessageFor(model => model.Product.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Product.FK_Category)
</div>
<div class="editor-field">
#*#Html.EditorFor(model => model.Product.FK_Category)*#
#Html.DropDownListFor(d => d.Categories, new SelectList(Model.Categories, "Id", "Name"))
#Html.ValidationMessageFor(model => model.Product.FK_Category)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Product.Description)
</div>
<div>
#{ Html.Telerik().EditorFor(m => m.Product.Description)
.Name("ProductCreateEditor")
.Encode(false)
.HtmlAttributes(new { style = "width: 500px;" })
.Tools(t => t.Clear()
.Bold().Italic().Underline().Separator().JustifyCenter().JustifyLeft().JustifyRight().JustifyFull())
//.Value((string)ViewData["ProductDescription"])
.Render(); }
</div>
<p>
<input type="submit" value="Stofna" />
<input type="button" value="Til baka" onclick="javascript:history.go(-1)"/>
</p>
</fieldset>
}
The problem I have is that every time I load my page the telerik editor appears but I can not write into the text area. (It looks like it were disabled) :(
Update
Remove this line from your Layout
<script src="#Url.Content("~/Content/rikona/js/jquery-1.3.2.js")" type="text/javascript"></script>
You only need one version of Jquery, they are conflicting is my best bet.
Everything else looks right
Remove this line
.Value((string)ViewData["ProductDescription"])
You are using EditorFor which pulls the value out of the model. So you only need to set the value in one place. You were trying to set it in two places, in the EditorFor and Value.
If you were using just Editor not EditorFor you can use Value
So choose to do EditorFor like so:
#{ Html.Telerik().EditorFor(m => m.Product.Description)
.Name("ProductCreateEditor")
...
.Render();
}
Or Editor
#{ Html.Telerik().Editor()
.Name("ProductCreateEditor")
...
.Value((string)ViewData["ProductDescription"])
.Render();
}
As John also states make sure the placement of your Telerik script is in the right place. It must be in the _Layout page at the bottom like so;
#(Html.Telerik().ScriptRegistrar().jQuery(false).DefaultGroup(group => group.Combined(true).Compress(true)))
</body>
</html>

Categories

Resources