How to include shieldui in asp.net mvc? - asp.net-mvc

I'm new to shieldui js and asp.net mvc and I'm doing some examples for a train. I have no problem including the js in a html file but I'm struggling to include it in asp.net mvc. Lets say i have jquery and shield ui in Scripts folder. I did reference Shield.Mvc.UI but I still cant access them via #(Html.XXXX).
Lets say i want to create ShieldCalendar using View.cshtml. The example is:
<div class="container">
#(Html.ShieldCalendar()
.Name("calendar")
.HtmlAttribute("class", "calendar")
.Min(new DateTime(2009, 2, 23))
.Max(new DateTime(2039, 3, 1))
.Value(DateTime.Now)
.Footer(fb => fb.Enabled(true).FooterTemlpate("{0:dd.MM.yy}")))
I'm a beginner and I may miss something fundamental for asp.net MVC.

Later findings: it looks like some time ago there weren't html helper extension methods for that. Are you sure you have something like that?
Question reference: shield ui chart: generate series dynamically? (where op is saying that he wrote a custom html helper for .net mvc)
Html helpers reference: http://www.tutorialsteacher.com/mvc/html-helpers
Are you sure you have html helpers in Shield.Web.UI namespace? (see this question too: Referencing the Shield UI ASP.NET MVC javascript modules)
1st approach
You can create a bundle with those two javascript files for now.
Open the App_Start\BundleConfig.cs, there you will have a RegisterBundles method where you can create a bundle with those two files.
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jqueryand")
.Include("~/Scripts/jquery-3.1.1.js"))
.Include("~/Scripts/shieldui.js");
// i don't know exactly the name of the library
}
And in your Global.asax.cs, you need to register this bundle:
In Application_Start method, add the following line:
BundleConfig.RegisterBundles(BundleTable.Bundles);
Then in your _Layout or your more specific view, you'll have to add #Scripts.Render("~/bundles/jquery")
More about this approach here: https://www.asp.net/mvc/overview/performance/bundling-and-minification
And here:
How do I add BundleConfig.cs to my project? (probably this question is very useful)
2nd approach
Use something like RequireJs for .NET, which will bring some features to your application, but will also add some complexity.
See my answer for the question below:
RequireJS - ASP.NET MVC Bundle Script
About this part of your problem:
but I still cant access them via #(Html.XXXX).
Maybe your intellisense is broken, you can give it a try after you add the script to the page/layout and after you make sure that you have
#using Shield.Web.UI
for your page/layout.

Related

Using razor views with jQuery validation with angularJS

I'm using AngularJS in my MVC application and trying to use the best of both worlds. I really like how you can in MVC set up your validation logic in your viewmodels and generate client side validation with jQuery validation in your razor views with little effort. I use AngularJS to get the SPA behavior with routing etc, but when I create a razor view that I use to inject into a page with:
<div data-ng-view="data-ng-view"></div>
then the jQuery validation stops working, even though the script files is references on the page where the view is injected. See below for my razor view:
#model BandViewModel
<div data-ng-controller="App.BandCreateCtrl">
<form name="startBandForm">
#Html.ValidationSummary(true)
<br />
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name, new { data_ng_model = "band.Name" })
#Html.ValidationMessageFor(m => m.Name)
<br/>
<input data-ng-disabled="startBandForm.$invalid" type="submit" data-ng-click="createBand(band)" value="Create"/>
</form>
</div>
First of all, IMO using Razor to render your templates is fraught with peril, at best. Generally you want to use static HTML for your page and directive templates, and then retrieve and post data as AJAX to your API. The ASP.NET web API is really good at this, actually. If your underlying model has validation, then bad web API calls will throw an exception, which you can catch in your $http or $resource handler and show to the user. Mixing standard HTTP form posts with AngularJS will be... difficult.
To achieve what you want, I think someone (not me) would have to write the AngularJS equivalent to jQuery Unobtrusive Validation library, which itself is using the jQuery Validate plugin. Not trivial. I personally don't see drop-in Angular validation happening soon, especially since it has more to do with markup and less to do with a JS configuration object.
Possibly you could re-initialize the validation when the view has finished loading using the $viewContentLoaded event. But please don't.
It pains me that everywhere I've looked we get the same replies: "HTML should just be a template". Perhaps, but I'm just not ready to delegate everything to JavaScript
Instead of using the anonymous object for passing the HTML attributes, try using the Dictionary
#Html.TextBoxFor(m => m.Name, new Dictionary<string, object>(){{ "data_ng_model", "band.Name" }})
Make sure is
Dictionary<string, object>
And not
Dictionary<string, string>
Otherwise the constructor will confuse it for
object HtmlAttribute
Not as pretty though... but it works for the most part.
Lastly, take in mind that if you include AngularJS after jQuery, then it will use jQuery for selectors.
To anyone still looking for a solution to this problem , there is a simple way to make it work.
var currForm = $("#myForm");
currForm.removeData("validator");
currForm.removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(currForm);
currForm.validate();
You could put this code in $viewContentLoaded or other places which are relevant in your code.
While I understand some of the views here which discourage MVC views being used as a templates for your Angular code. My reason being its not not a natural way of doing things in angular and hence there are chances that you will run into issues like this one. But if you benefit from using MVC views as templates its not a path to hell. IT works and can benefit you as well. I have 2 use cases in my project where using MVC views make a lot of sense.
My project actually has a requirement where a client can turn of the required validation on certain field , for this I use the MVC custom data annotation validator which allows me to add or remove the data annotation at the time of rendering the view using a single class , if you were to build the same flexibility in angular , you would have to write a lot more code. So MVC views work great here for me as Custom Data Annotations are triggerd by the DisplayFor and EditorFor helpers
We are heavily invested in Internationalization and while angular is great at other stuff internationalization is not its strong suite ( at the time of writing this atleast )I still feel the internationalization support in MVC with .RESX works great and has been here long . This again uses the data annotation power of the DisplayAttribute.
TLDR : MVC views as templates may give you a few unexpected problems but are worth it if you are really using the full power of the data annotation pipeline created by Microsoft.
Hopefully someone comes up with a Angular HTML Helpers library in the future this would be much simpler.
Maybe using Angular for validation can be less painful than you think. Using a couple of custom directives, you could easily get something quite close to Razor with markup as simple as:
<validated-input name=username display="User Name" ng-model=model.username required</validated-input>
Check out my sample here and its inspiration here. It only implements required and number at the moment, but customizing it should be easy.
You can use ngval library. It brings data annotations to client side as angularjs validation directives.

How to use ScriptManager with Razor in MVC 4?

I used ScriptManager in .aspx page to Maintain URL history in .Net i.e.
on aspx page i put this script after form tag
> <asp:ScriptManager runat="server" ID="ScriptManager1" EnablePartialRendering="true"
> EnableHistory="true">
> </asp:ScriptManager>
and in my .js file i put this code
Sys.Application.add_navigate(function (sender, e) {
navigate(sender, e);
});
Sys.Application.addHistoryPoint(objOut, null);
Now same thing i want to use in MVC 4 with Razor
I used MicrosoftAjax.js for ScriptManager and .js code is same.
but i am getting issue on callback.
let me explain you with example:
suppose Actual URL is
www.websitename.com/cat/30/
anchor tag link on page is
www.websitename.com/cat/30/?q=10
once callback perform anchor tag link becomes
www.websitename.com/?q=10
I mean after callback "cat/30/" is missing from link.
can anyone tell me what I am doing wrong.
Thanks.
Ashu
ScriptManager is part of ASP.NET Webforms. It is not available in ASP.NET MVC. They are two completely different frameworks.
There is a port of ScriptManager to ASP.NET MVC which is available here. It might provide what you are looking for.

Share a razor declarative helper between multiple mvc web projects

Let's say I have 2 MVC web projects (web1 and web2) and 1 project containing shared views (common) (using the razorgenerator of David Ebbo)
web1 and web2 both have a test.cshtml file. Several blocks of code in both test.cshtml files are exactly the same.
I'm trying to find out if it's possible to share a declarative helper (#helper) between several cshtml files which are in DIFFERENT projects. So putting a cshtml file in my App_Code does not help (I would need to have 1 in each web project, which is obviously not what I want).
I know I could create a bunch of shared partial views in my 'common' project, but it seems kinda overhead to create 20 cshtml files that each contains a very small portion of html.
I know I can create a standard helper method (static string GenerateAPieceOfHtml(this HtmlHelper helper, ....)), but there I loose the ease of writing html as you can do it in a cshtml file.
For a short while I thought I bumped into an answer that would allow me to do it. But as I wrote in a comment, that code did not compile for me.
I hope my question is clear :)
[Update]
As csharpsi asks in a comment.. I did try out the code from the other post, but it did not spit out any HTML for me. Since I started to think that that answer should probably do the trick since it has 13 upvotes, I decided to give it a second try..
Again I didn't get any output, but then I tried it a little bit different.. and success!
I was trying this (which doesn't spit out any html on the page):
#{ new Test().DoSomething(Model); }
This is the version that DOES WORK:
#{
var html = new Test().DoSomething(Model);
#html
}
Other version that works:
#(new Test().DoSomething(Model))
What should I do with this question? Delete it? Write an answer myself?
Why are you trying to use razor helper for this anyway ? Razor helpers are one-particular-viewengine hack, your application shouldnt rely on them on many places (even amongst different websites). In this case, be sure to use standard MVC way - HTML helper. These you can easily share between websites, for example you can make your own class library full of them.

MvcContrib FluentHtml With Razor?

I'm wondering does the latest release of MvcContrib work with the Razor view engine? I referenced the MvcContrib assembly and the FluentHtml assembly, then I added the required namespace to the ~/View/Web.config as suggested here by Darin. But still, no matter how much I try use the FluentHtml extensions in my views, it doesn't work. (nothing shows up in intellisense when I start with a dot after the html helper)
Am I missing anything?
P.S: this is the first time I use MvcContrib.
I wrote a short blog that post covers using FluentHtml with Razor.
Regarding intellisense, you will only get intellisense for FluentHtml methods on "#this." (not "#Html.") and it only list the strong-typed helpers on views that implement IViewModelContainer<T> (such as ModelWebViewPage<T>). Another possible issue is Resharper. There is a workaround for that.
I´m using mvccontrib and following darin answer it has to work. The steps I followed were:
copy-pasted in bin folder mvccontrib.dll and mvccontrib.fluent.dll
make a reference in references to those dll creating a reference for mvccontrib and mvccontrib.fluent.
two namespaces with the following names:
add namespace="MvcContrib"
add namespace="MvcContrib.FluentHtml"
in my controller I include using MvcContrib.Pagination;
finally I used in my view:
#using MvcContrib.UI.Pager
#using MvcContrib.Pagination
and rebuild.
hope it helps..

Using JQuery with ASP.NET MVC Framework

I have searched the forum, and google for this topic. Most of the articles are talking about using JSON to call the controller/action on the server and do ajax effect on the result.
I am trying to use some very basic JQuery features, like the JQuery UI/Tabs, and JQuery UI/Block for a dialog window. I cannot get these simple samples to work in my MVC project. Any ideas how I should modify these samples? I only need these basic feature now and I can go from here.
Thanks!
Actually I just got it working. The problem is that I need to modify the path to an absolute path to the view page because the relative path doesn't work with the MVC routes {controller}/{action}/{id}.
Thanks!
For info, re the relative path issue - I discussed this here (the same concept applies to any page, not just master pages). The approach I used is like so:
1: declare an extension method for adding scripts:
public static string Script(this HtmlHelper html, string path)
{
var filePath = VirtualPathUtility.ToAbsolute(path);
return "<script type=\"text/javascript\" src=\"" + filePath + "\"></script>";
}
2: when needed (for example in the <head>...</head>) use this method:
<%=Html.Script("~/Scripts/jquery-1.2.6.js")%>
The advantage of this is that it will work even if the web app is hosted in a virtual directory (i.e. you can't use "/Scripts" because you aren't necessarily at the site root) - yet it is a lot clearer (and less messy) than the full script with munged src, i.e.
<script ... src="<%=Url.Foo(...)%>"></script>
I just implemented the jquery autocomplete textbox in one of my asp.net project. I only had to import the js file and drop some code into my aspx page. Could you be more detailled about what sample you are trying to run?
This is quick response!!
I am trying to run this "Simple Tabs" on this page:
http://stilbuero.de/jquery/tabs/
I think it is the same with this one: http://docs.jquery.com/UI/Tabs
I just copied and pasted the whole thing into my MVC view page, with corrected path to the jquery.js and .css files, but the content in the tabs all show up together (two of them are supposed to be hidden). My understanding is that this simple jquery plugin just show and hide content.
I had the exact same problem with the jquery thickbox plugin, that the item marked as "hidden" (the dialog box) will always show up in my MVC view page.
I can understand some of the MVC+Jquery+json articles, but I don't understand why the hide/show doesn't work.
Thanks!
I just made a walkthrough on how to do this:
http://blogs.msdn.com/joecar/archive/2009/01/08/autocomplete-with-asp-net-mvc-and-jquery.aspx

Resources