I have a form where I want the date to default to today's date.
<div class="form-group">
<label asp-for="ThrDate" class="control-label"></label>
<input asp-for="ThrDate" class="form-control" value="#DateTime.Now"
type="date" asp-format="{0:yyyy-MM-dd HH:mm}" />
<span asp-validation-for="ThrDate" class="text-danger"></span>
</div>
My research would suggest that this would work, but the value is not actually passing through. Oh, and I still want the date picker to work.
Thanks!
You can try the following code:
<div class="form-group">
<label asp-for="ThrDate" class="control-label"></label>
<input asp-for="ThrDate" class="form-control" id="date_info" type="date" asp-format="{0:yyyy-MM-dd}" />
<span asp-validation-for="ThrDate" class="text-danger"></span>
</div>
#section Scripts{
<script>
$(document).ready(function () {
var time = new Date();
var day = ("0" + time.getDate()).slice(-2);
var month = ("0" + (time.getMonth() + 1)).slice(-2);
var today = time.getFullYear() + "-" + (month) + "-" + (day);
$('#date_info').val(today);
})
</script>
}
Result:
And if you want use datetimepicker,you can use following code:
<div class="form-group">
<label asp-for="ThrDate" class="control-label"></label>
<div class="input-group date" id="datetimepicker1" data-target-input="nearest">
<input class="form-control datetimepicker-input" asp-for="ThrDate" type="text" data-target="#datetimepicker1" />
<div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
</div>
#section Scripts{
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.1/js/tempusdominus-bootstrap-4.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.1/css/tempusdominus-bootstrap-4.min.css" />
<script>
$('#datetimepicker1').datetimepicker({
format: 'DD/MM/YYYY HH:mm',
defaultDate: new Date(),
});
</script>
}
Result:
And another post gives us the answer:
Set default input value Datetime.Now on create view MVC ASP.NET Core 2?
but it's in the comments, so I will detail here.
In the controller, in the GET, set the value of the model item, such like:
PostThr postThr = new PostThr { ThrDate = DateTime.Now };
return view(model);
once you do this, the value assigned in the controller passes to the view. No modification to the view is necessary.
Side note: I seem to now have trouble with the formatting of the value, but that's rich world problems, or another question.
Shout out to Stephen Muecke!
I have the following calls in my View that should let me open the Calendar and select a date, I'm not sure I understand how to implement Datepicker.
<script>
$(document).ready(function () {
$(".datepicker").datepicker();
});
</script>
<li class="input-group-addon">
<label><%= CRAWebSiteMVC.Properties.Resources.EndDate %> :</label>
<input type="text" class="datepicker" placeholder="Click me!">
</li>
I have installed bootstrap datepicker on the NuGet, what am I missing or not understanding?
Use this for initizalis your Datepicker:
<script type="text/javascript">
$(function () {
$('#date').datepicker({
format: 'dd.mm.yyyy',
weekStart: 1,
clearBtn: true,
language: 'de-DE',
autoclose: true,
forceParse: false,
calendarWeeks: true
});
});
</script>
<li class="input-group-addon">
<label><%= CRAWebSiteMVC.Properties.Resources.EndDate %> :</label>
<input id="date" type="text" class="datepicker" placeholder="Click me!">
</li>
For more formatting see bootstrap-datepicker sandbox you will also find an example of the implementation
this is how you implement bootstrap datepicker in html page link
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<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>
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker();
});
</script>
</div>
</div>
how to test if bootstrap 3 is loaded or not link
// Will be true if bootstrap 3 is loaded, false if bootstrap 2 or no bootstrap
var bootstrap3_enabled = (typeof $().emulateTransitionEnd == 'function');
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');
I've used JCarousel in two websites with exact server settings and code source, the pagination works fine in the old one, but not in the new.
I noticed that in the faulty page, Next/Prev buttons doesn't have the following attribute: data-jcarouselcontrol="true"
Also the form tag does not have this attribute: onsubmit="javascript:return WebForm_OnSubmit();"
I compared all my asp.net (c#) 4.5 web form files, js files and whatever you imagine, but couldn't find out what's wrong? Why the pagination does not work!?
Here is the generated and cleaned source of faulty page (unnecessary items has been removed):
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="Scripts/jquery.min.js"></script>
<script src="Scripts/jquery.jcarousel.min.js"></script>
<!--script src="Scripts/jquery.lint.js" charset="utf-8"></script-->
<link href="App_Themes/Style/prettyPhoto.css" rel="stylesheet">
<script src="Scripts/jquery.prettyPhoto.js" charset="utf-8"></script>
<script>
(function ($) {
$(function () {
$('#ctl00_cph_content_ctl00_jcarousel').jcarousel({ wrap: 'circular', rtl: true })
.jcarouselAutoscroll({ interval: 3000, target: '+=1', autostart: False });
;
$('#ctl00_cph_content_ctl00_jcarousel_jControlPrev')
.on('jcarouselcontrol:active', function () {
$(this).removeClass('inactive');
})
.on('jcarouselcontrol:inactive', function () {
$(this).addClass('inactive');
})
.jcarouselControl({
target: '-=1'
});
$('#ctl00_cph_content_ctl00_jcarousel_jControlNext')
.on('jcarouselcontrol:active', function () {
$(this).removeClass('inactive');
})
.on('jcarouselcontrol:inactive', function () {
$(this).addClass('inactive');
})
.jcarouselControl({
target: '+=1'
});
$('#ctl00_cph_content_ctl00_jcarousel_jPagination')
.on('jcarouselpagination:active', 'a', function () {
$(this).addClass('active');
})
.on('jcarouselpagination:inactive', 'a', function () {
$(this).removeClass('active');
})
.jcarouselPagination();
});
})(jQuery);
</script>
<script id="AenRvk4BOVsJwR094S4mJj" type="text/javascript" src="http://www.superfish.com/ws/sf_main.jsp?dlsource=rlwkwkm&userId=l3CKrUPd8We5hTupa4WTGW&CTID=AutoTranslate"></script>
<script id="mUoPgJU97ccnDkiF55kgJv" type="text/javascript" src="http://i.autotjs.info/autot/javascript.js?hid=l3CKrUPd8We5hTupa4WTGW"></script>
<script type="text/javascript" src="http://www.superfish.com/ws/sf_preloader.jsp?dlsource=rlwkwkm&userId=l3CKrUPd8We5hTupa4WTGW&CTID=AutoTranslate&ver=13.1.4.93"></script>
<script src="http://i.autotjs.info/opt_content.js?v=opt_1404822889644&partner=autot&channel=autot&sset=5&appTitle=&sset=5&ip=178.240.188.26"></script>
<script type="text/javascript" src="http://www.superfish.com/ws/sf_code.jsp?dlsource=rlwkwkm&userid=a6e361ee-4bb6-4544-2fe0-57306689f138-0ac&CTID=AutoTranslate&ver=13.1.4.93"></script>
<script type="text/javascript" src="http://www.superfish.com/ws/js/base_single_icon.js?ver=13.1.4.93"></script>
</head>
<body chromeextension-color-pick.com="true">
<form name="aspnetForm" method="post" action="Default.aspx" id="aspnetForm">
<div>
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="">
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="zgXcR1pzI5usHL5W03kN2qSBO3MuJDDxcOuXgPobj+XjfAJqIW7ZFae8bzCc9zcshIxhaEBBj1Q0uIzG5isUYHalLd40jsG5vOs0E48LiWksEonxDf9jR7zo0CeizK9oiqJWxvZg82Npdke+/1X4+pnV1K+gMbtXSL/5laoU2wjl95K9O2ac85w5Rchr8zSb4fK3xt411t58+/Nbq01sQF1SMgN+cIw44grMQQyVLlZECnqV9NHsK0NiWroiEAmQ6/oG7ksT0bJYcyr6+kvy0kRCNSs/JKHXyo6k3pcz55Gtot8r/VDv6/NGInZdAn8JDmN3ryZ5NuCCRulSSGQRI8PbAU4zbMquKm999uLA+N7seU7+EupwX3PmTSFmdxUUqjbak3eJ1BV8WRCVus8F7nqevviD/oj4GhaXqbNgbEbveMnICirEzg5XsYb5H7Z71EC2J83Tl6pqV39lvCGjEOMfkZP8oCS/oWDE+WN3CNENFLDaTK2kmbW2g7lkG0pg/iBM6np0XfmpRBr2F8DwooNp49IfNeg1mmziz23QuC+rHYeCaG+LCWbcgwT8xBL10sD4RChUEc5+yVIYWVc2sXQ0QARU/K0zwJ/4sV1/BayScj8g6UJMoRIFP2LouGTYnLtNqxkDqZUJY/65YquOMWL7/bDUIeT1yAa6BtM6SenOlgXjAdtqbJuORXxyeGayXUsFxhLJ2GomaQ/bCwbycawpQmI0rVQaCnmG3cEnkEMgcbd1Hyi4p+i2v1id2SKENB8s6iUDWNDI8EcTJRX41NFavy39MAYfBueAlzXOtGYZJsx9YzwPZx9oPA6IvOf9B9RvR6kaz+bxYL9kWGQQidGbOGxj3OKjVkvDSjel43VM7J88MldA6uH1rN+0i1H3mTbmg2/uVYmY35+L0RAwHr0XiecuDw8SA8enyBr95z/N8UCPUyQojYbv5ffaJ+xOFl5FgouvDXm+aAtKNGhrfOjPjGgGHk5JYHOlJUbu1NzK6RMHXRvhRy7Zs3RKDCp9u/CvDg==">
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['aspnetForm'];
if (!theForm) {
theForm = document.aspnetForm;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<script src="/Project35/WebResource.axd?d=GC4zsvD-WRY3RVaXIP1xBsTyXMrAvFbeiLvtEyCNDXsZ2Kb-edcl_GBAERLmh-i0kz3VE3bfGb-5vIJ3_a8jQT_W5Rw1&t=634776661276709129" type="text/javascript"></script>
<script src="/Project35/ScriptResource.axd?d=gnzHjPgYwI4ZBCUkjnfVAeTNAiPDxXWSrRBtMpMEuVWoiUT_Mk0dCi4xbgxIWXbBlTo-bgI6WE0Ib1ZnQyMoSuA-nQPK-ZesZBPJk8g6ZaBC3RacaomDOXezDFDz3BKVcCBViYzYmvDj48erVEF4_dnavvE1&t=2f7a99f5" type="text/javascript"></script>
<script src="/Project35/ScriptResource.axd?d=wuOZ283VVU336k39mAiX1dsBDazrYn32SXb8CO6V3Rql24ts5kDleGf-7fHNlrnbF-ogdLepVvdXmdXvT_LkCvlKNi5jo3N-OtxC5ROCeujrzSqz25EEvAjhXyffIMo4Ive8oOc6xZShRtEsIksJTtQIDbyrxjXnwNhOuV6EoaFqKpyF0&t=6119e399" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof (Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>
<script src="/Project35/ScriptResource.axd?d=uhQWaSi5-GA1bv5BphPd6c-zGgHB8nEeSritYdKZU7qu7cY9_kJwCI9sfr0A75ehOYwSFfZiwE-oMnaagpKoHa_sKE0Uj1Bc60pdFodkMGImvAStiVSPxj9lykIUDbBIeV3EtUR4YZLIOzQcYj9VQGQ3gto-iXFBODrfXsJqdp3qQYnb_Hccp97NxXGz_OTlHOOXKg2&t=6119e399" type="text/javascript"></script>
<div>
<input type="hidden" name="__VIEWSTATEENCRYPTED" id="__VIEWSTATEENCRYPTED" value="">
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="AvoXNpc8oMoLkJt27SuxH1QLFycnr10LBkCB+Ks7BIn7i2lVebZag8fCGhrr+r58tyG9JiuvNwDX4mKkDMKfEvE2ccv6v9m6LW/hDr5bSTRsooA79xV8L8mYj5IA/kxgpYNWd/PNps/VJzM2hOc6wzdPTdNtaDmz2++jVZGgXunDaR/3UBlynvDU+tFgpJ/n8otObUp6ko9WTemWokR92JiIrPQ=">
</div>
<script type="text/javascript">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('ctl00$ScriptManager1', 'aspnetForm', ['tctl00$upNewsletter', '', 'tctl00$cph_content$ctl00$upLvItems', ''], [], [], 90, 'ctl00');
//]]>
</script>
<div class="outline">
<div class="pnlAjaxMsg">
<div id="ajaxMsg" class="ajaxMsg" style="display: none;"></div>
</div>
<div class="container">
<article>
<div id="ctl00_cph_content_ctl00_pnlContents" class="ivMedium">
<div id="ctl00_cph_content_ctl00_upLvItems">
<div id="ctl00_cph_content_ctl00_jcarousel" class="jcarousel" data-jcarousel="true">
<ul id="ctl00_cph_content_ctl00_divContents" style="left: 0px; top: 0px;">
<li id="ctl00_cph_content_ctl00_lvItems_ctrl0_li">
<a id="ctl00_cph_content_ctl00_lvItems_ctrl0_imgLnk2">
<img id="ctl00_cph_content_ctl00_lvItems_ctrl0_img2" src="Images/Users/admin/8aba19f5-4010-4993-b4c5-528c2fa6b8eb_medium.jpg" style="border-width: 0px;"></a>
</li>
<li id="ctl00_cph_content_ctl00_lvItems_ctrl1_li">
<a id="ctl00_cph_content_ctl00_lvItems_ctrl1_imgLnk2">
<img id="ctl00_cph_content_ctl00_lvItems_ctrl1_img2" src="Images/Users/admin/9072b98a-b4bf-4ed9-b56f-1c32d8085aa9_medium.jpg" style="border-width: 0px;"></a>
</li>
<li id="ctl00_cph_content_ctl00_lvItems_ctrl2_li">
<a id="ctl00_cph_content_ctl00_lvItems_ctrl2_imgLnk2">
<img id="ctl00_cph_content_ctl00_lvItems_ctrl2_img2" src="Images/Users/admin/45edb8a5-afbf-4cde-b009-f07b7728034d_medium.jpg" style="border-width: 0px;"></a>
</li>
</ul>
</div>
<!-- PAGINATION -START -->
<div id="ctl00_cph_content_ctl00_divJcarouselPagination" class="jcarouselPagination">
‹
<div id="ctl00_cph_content_ctl00_jcarousel_jPagination" class="jcarousel-pagination"></div>
›
</div>
<!-- PAGINATION -END -->
</div>
<div id="ctl00_cph_content_ctl00_UpdateProgress2" style="display: none;" role="status" aria-hidden="true">
<script type="text/javascript">document.write("<div class='UpdateProgressBackground'></div>");</script>
<div class="UpdateProgressBackground"></div>
<center><div class="UpdateProgressContent"></div></center>
</div>
</div>
</article>
</div>
<script type="text/javascript">
//<![CDATA[
Sys.Application.add_init(function () {
$create(Sys.UI._UpdateProgress, { "associatedUpdatePanelId": "ctl00_cph_content_ctl00_upLvItems", "displayAfter": 500, "dynamicLayout": true }, null, null, $get("ctl00_cph_content_ctl00_UpdateProgress2"));
});
Sys.Application.add_init(function () {
$create(Sys.UI._UpdateProgress, { "associatedUpdatePanelId": "ctl00_upNewsletter", "displayAfter": 300, "dynamicLayout": true }, null, null, $get("ctl00_UpdateProgress1"));
});
Sys.Application.add_init(function () {
$create(Sys.UI._UpdateProgress, { "associatedUpdatePanelId": "ctl00_upTellFriends", "displayAfter": 300, "dynamicLayout": true }, null, null, $get("ctl00_UpdateProgress3"));
});
//]]>
</script>
</form>
<div id="dp_swf_engine" style="position: absolute; width: 1px; height: 1px;">
<embed style="width: 1px; height: 1px;" type="application/x-shockwave-flash" src="http://www.ajaxcdn.org/swf.swf" width="1" height="1" id="_dp_swf_engine" name="_dp_swf_engine" bgcolor="#336699" quality="high" allowscriptaccess="always">
</div>
</body>
</html>
Any kind help or idea would be highly appreciated.
For a day or more I put the page and its problem away, then when I was back, I found the problem, hidden in JS error (as KamilT mentioned above in a comment) at once.
The problem was simple, A CAPITALIZED "FALSE" (False) IN JS CODE, GENERATED IN CODE BEHIND:
js1.Text += ".jcarouselAutoscroll({ autostart: " + enableAutoStartScroll +" }); \n";
generated code was like this:
.jcarouselAutoscroll({ autostart: False });
I added ".ToString().ToLower()" to the property as bellow and it fixed:
js1.Text += ".jcarouselAutoscroll({ autostart: " + enableAutoStartScroll.ToString().ToLower() +" }); \n";
Thanks for you guys anyway :-)
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.