I've created a new asp.net MVC app in VS.NET 2013. In _Layout.cshtml, I have a reference to the angularjs library (Google developer site). I also define a controller called "con1" and create a variable.
_Layout.cshtml:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<script type="text/javascript">
function con1($scope) {
$scope.somestring = "some string";
}
</script>
Index.cshtml:
<div>
{{1+1}}
</div>
The above works fine and renders the result of "2".
When I change the div to the following and start trying to access the somestring variable in the controller, I get the actual AnguarJS code rather than the result.
<div ng-controller="con1">
{{1+1}}
</div>
Output: "{{1+1}}"
Any idea why adding the controller reference breaks it? This seems to be VS.NET specific. I have a jsfiddle here that works fine: http://jsfiddle.net/jpswdzxu/. That is basically the output from the VS.NET project.
You need to define the Angular Application, or it won't work:
<script type="text/javascript">
var myApp = angular.module('myApp',[])
.controller('myAppCtrl', function($scope) {
$scope.somestring = 'teststring';
});
</script>
Then, the HTML should be:
<body ng-app="myApp">
<div ng-controller="myAppCtrl">
{{somestring}}
</div>
</body>
Or, using your jsfiddle, it would be:
<div ng-app="myApp" ng-controller="myAppController">
{{1+1}}
<br>
{{somestring}}
</div>
and:
angular.module('myApp',[])
.controller('myAppController', function ($scope) {
$scope.somestring = "some string";
});
Good Luck!
Related
I'm using the angular-rails-templates plugin to preload html files in the assets/javascript/templates (sprocket fix is not working)
When I use the inspector, I can see that the CacheTemplate is being triggered:
// Angular Rails Template // source: app/assets/javascripts/templates/bannertime.html angular.module("templates").run(["$templateCache", function($templateCache) { $templateCache.put("bannertime.html", '<section id="landing-page-banner">') }]);
My app.js
app = angular.module('logged_out', ['templates', 'ng'])
app.controller "logged_out", ($scope) ->
$scope.banana = "hello banana face"
My index.html.erb
<div ng-app="logged_out" ng-controller="logged_out">
<div class="container-fluid">
<div ng-include="bannertime.html"></div>
</div>
</div>
Can someone please explain to me why ng-include is impossible to make work? I've been working on this for 3 days now.
Damn you world!
ng-include requires two different quotes ?!?!?!?!
Once I changed <div ng-include="bannertime.html"> to <div ng-include=" 'bannertime.html' "> everything worked.
Goddddd damnt
With an MVC project containing _layout.cshtml with bundles loaded, clicking around loads the Layout and bundles every time a view is loaded. Is there any build-in mechanism that I can use to load that stuff only initially, so that RenderBody() only loads the content I don't have yet (not reloading Layout)? Is this where partials come in?
If partials are the right way to handle it, does this mean I need to have two versions of each controller method (One with Layout, one without)? Any tips here would be great.
As far as I know there's no built-in mechanism to load the layout page only at once. You can do it using client-side approach if you want that layout will be loaded only at once so that it would be lighter for the server. Here's the step. Create MVC 4 application.
In your _Layout.cshtml add a div that will hold the html page you want to load. In my case "pageholder"
<div id="body">
<div id="pageholder">
#RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
#RenderBody()
</section>
</div>
</div>
Add this script in your _Layout.cshtml
#Scripts.Render("~/Scripts/common.js")
<script type="text/javascript">
$(document).ready(function() {
$('.pagelink').click(function() {
var settings = {
'url': $(this).attr('url'),
'type': 'GET',
'dataType':'html'
};
get_html(settings);
});
});
</script>
Modify your menu link
<nav>
<ul id="menu">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
<li>About</li>
<li> Contact</li>
</ul>
</nav>
Add js file and name it common.js and put this content
function get_html(settings) {
settings.success = function(data) {
$('#pageholder').empty().html(data);
};
settings.error = function (xhr, ajaxOptions, thrownError) {
alert(xhr.statusText);
};
$.ajax(settings);
}
Set Layout = null; both About and Contact views
#{
ViewBag.Title = "About";
Layout = null;
}
Run the application and test the About and Contact pages
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>
I am trying to do the following:
The object I give to the Viewpage has a list, I do a foreach in the HTML and I create a number of components. Now, I want the IDs of those components to somehow be linked to the object from the List.
(The reason I am trying to do this is because I want to show a button, when they press that button the shown content will change and they should see something else, I will use javascript to achieve this)
Therefor I am trying to make the id of those components dynamic, by for example stating
id="button <%= item.id%>" however this does not seem to work. I have searched alot on google but I haven't found a solution yet which is why I turn to you guys.
I'll link my code as well, I deleted some of the parts that were unnecessary (but added the javascript):
<script type="text/javascript">
function AlterPanel(thePanel) {
var panel = document.getElementById("region"+thePanel);
panel.style.display = 'block';
var button = document.getElementById("button"+thePanel);
button.style.display = 'none';}
</script>
<%foreach (TeamDTO team in Model.List.Teams)
{ %>
<a id="button<%= team.Number %>" onclick="AlterPanel(<% team.Number%>)">
Add member</a>
<div Visible="false" id='region<%= team.Number %>' runat="server">
Please select one:
<%: Html.DropDownListFor(V => V.memberID, new SelectList(Model.members, "ID","Name")) %>
</div>
<% } %>
I eagerly await a reply and thank you in advance.
I guess your Queastion is:
-you have some "button DropDownList" pair, button is visiable, DropDownList is invisible, now if user click the button then DropDownList will showup.
OK, now your View maybe :
<%foreach (TeamDTO team in Model.List.Teams)
{ %>
<a onclick="AlterPanel(<% team.Number%>)">
Add member</a>
<div id="region<%= team.Number %>" style="display:none">
Please select one:
<%: Html.DropDownListFor(V => V.memberID, new SelectList(Model.members, "ID","Name")) %>
</div>
<% } %>
I use JQuery in javascript part like this:
<script type="text/javascript">
function AlterPanel(thePanel) {
$("#region" + thePanel.toString()).css("display", "block");
}
</script>
Don't forget include the following file in View():
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery-1.4.1.min.js") %>"></script>
if the answer is not what you want, let mt know and I can help you~ :)
I have setup a simple example to show a form inside a jquery UI dialog and wish to enable inline client side validation on that form
I have then added the scripts to my master page
<script type="text/javascript" src="<%: Url.Content( "~/_assets/js/jquery-1.4.3.min.js" )%>"></script>
<script type="text/javascript" src="<%: Url.Content( "~/_assets/js/jquery.validate.min.js" )%>"></script>
<script type="text/javascript" src="<%: Url.Content( "~/_assets/js/MicrosoftMvcJQueryValidation.js" ) %>"></script>
and then I have enabled Client Side Validation through the following code
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm() { %>
<% } %>
Then, I dont know how to enable inline validation for every input so when the user leaves the focus from any of them validation occurs.
The client side validation seems to work only after I have done a submit. But that is not a "client side validation" as the attributes get validated from my server code...
Any suggestion?
Finally I have got through the solution.
First of all, my forms were never binded to validation callbacks provided by the code inside the MicrosoftMvcJQueryValidation.js script. This because I am using jQuery dialogs and the form is inside the dialog while the script included in the master page.
My first attempt toward the solution has been to modify the MicrosoftMvcJQueryValidation.js. In particular I have added a function EnableClientSideValidation() where I moved the code that was in the $(document).ready function as in the following code sample
function EnableClientSideValidation() {
var allFormOptions = window.mvcClientValidationMetadata;
if (allFormOptions) {
while (allFormOptions.length > 0) {
var thisFormOptions = allFormOptions.pop();
__MVC_EnableClientValidation(thisFormOptions);
}
}
}
$(document).ready(function () {
EnableClientSideValidation();
});
Then I have called the same function inside a script block that I have placed in the dialog markup code $(document).ready() function
With the help of firebug I have placed a breakpoint inside the EnableClientSideValidation() function and then experienced the fact that was called only when the main page was ready but not from the dialog. This was due to the fact that I had my "dialog" script block inside the <form>...</form> tag and so the script did not worked.
Code like this
<% using (Html.BeginForm()) { %>
//DIALOG FORM CODE WAS HERE
<script type="text/javascript">
$(document).ready(function () {
EnableClientSideValidation();
});
</script>
<% } %>
has been changed to
<% using (Html.BeginForm()) { %>
//DIALOG FORM CODE WAS HERE
<% } %>
<script type="text/javascript">
$(document).ready(function () {
EnableClientSideValidation();
});
</script>
Finally everything started working! I would like to thanks vandalo and kdawg for helping in finding a solution. There was something still missed but your answers have stimulated my head.
I am posting this for other that can have the same problem.
OK, so here's what I did to get MicrosoftMvcJQueryValidation to work for me in an AJAX/PartialView environment. It's relevant, because essentially both instances (my AJAX/PartialView stuff and your onBlur triggering) require explicit control of when the validation methods are called. I'll try my best to capture everything you need to do, because I ended up having to edit my MicrosoftMvcJQueryValidation.js file to get it AJAX-enabled. However, I don't believe any of my edits are required for what you want.
The key lies in being able to access the validation functions that MicrosoftMvcJQuery generates. Fortunately, it adds it to the form element via a property called validationCallbacks.
In my custom submit function, I access and call these callbacks like this (form is the DOM element, not a jQuery object):
// this taps into the mvc clientside validation functionality.
// this is a roundabout way of calling jquery.validate() as
// that is what's going on the in callback() function
validationCallbacks = form.validationCallbacks;
if (validationCallbacks) {
for (i = 0; i < validationCallbacks.length; i += 1) {
callback = validationCallbacks[i];
if (!callback()) {
// subsequent submit handlers should check for
// this value before executing
event.cancelBubble = true;
return false;
}
}
}
I then have my context-specific submit functions check event.cancelBubble before continuing.
For your case, you could have this code be called on the blur event for each input in your form. Granted, it's not the most efficient solution, as each function in the validationCallbacks array validates the entire form, but it will trigger validation on each blur. (validationCallbacks is an array to support multiple forms that require validation.)
Sorry it's not super specific to your situation, but it should get what you need.
I have my earlier answer about how to manually call the validation callbacks created by MicrosoftMvcJQueryValidation.js, however, there may be a simpler answer. (I'm leaving my first answer as future reference for anyone.)
The options for jQuery's Validation plug-in give you the ability to change which event triggers validation. From http://docs.jquery.com/Plugins/Validation/validate#toptions, we have the following option properties: onsubmit, onfocusout, and onkeyup. You should be able assign these options values appropriately and have jQuery Validation behave like you want.
You MAY need to tweak MicrosoftMvcJQueryValidation.js to allow for the setting of options for when it calls validation. I had to do that with my edited copy.
You can follow this example:
There's a problem with the script in MicrosoftMvcJQueryValidation.js which must be updated.
Change the script MicrosoftMvcValidation.js in the step 3.
Model:
Namespace Models
Public Class Customer
Private _Name As String = ""
<DisplayName("Name")> _
<Required(ErrorMessage:="{0}: Mandatory field.")> _
<StringLength(10, ErrorMessage:="{0}: Max lenght 10.")> _
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
Private _Surname As String = ""
<DisplayName("Surname")> _
<Required(ErrorMessage:="{0}: Mandatory field.")> _
<StringLength(10, ErrorMessage:="{0}: Max lenght 10.")> _
Public Property Surname() As String
Get
Return _Surname
End Get
Set(ByVal value As String)
_Surname = value
End Set
End Property
End Class
End Namespace
<%# Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage(Of MvcApplication1.Models.Customer)" %>
<%# Import Namespace="MvcApplication1.jQuery" %>
...
<% Html.EnableClientValidation()%>
<% Using (Html.BeginForm())%>
<fieldset id="FormEditSet">
<div>
<div>
<%=Html.LabelFor(Function(m) m.Name)%>
<%=Html.EditorFor(Function(m) m.Name)%>
<%=Html.ValidationMessageFor(Function(m) m.Name, "*")%>
</div>
<div>
<%=Html.LabelFor(Function(m) m.Surname)%>
<%=Html.EditorFor(Function(m) m.Surname)%>
<%=Html.ValidationMessageFor(Function(m) m.Surname, "*")%>
</div>
</div>
</fieldset>
<input type="image" src="<%=Url.Content("~/Content/Images/page_save_big.png")%>"
value="Save" title="Save" style="border: none;" />
<%End Using%>
Html.ValidationSummaryJQuery is a new extension method you have to define (follow the example).
Remember to put the script at the bottom of the page:
<script src="<%=Url.Content("~/Scripts/MicrosoftAjax/MicrosoftMvcJQueryValidation.min.js")%>" type="text/javascript"></script>
You need to bind your input fields to properties in your controller, then use the Required attribute on your properties - see http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx for an example.