I'm currently stuyding MVC-5 ASP.NET and following this tutorial: https://www.youtube.com/watch?v=Fu9v2MIDlTA
I have successfully created my view and controller and therefore my HeLLO WORLD display. Now I'm currently in part 2 of the tutorial wherein I'm passing my data from controller to View.
Here are the codes:
Home Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication2.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult ShowHome()
{
ViewData["CurrentTime"] = DateTime.Now.ToString();
return View("Home");
}
}
}
View:
#{
ViewBag.Title = "Home";
}
<html>
<head>
<title>
WELCOME TO MVC 5
</title>
<body>
<div>
This is my homepage! <br/>
TIME: <%= ViewData["CurrentTime"]%>
</div>
</body>
</head>
</html>
The question is: Why is it that when I type the part:
<% %>, my ide is not reading it? I mean, the speaker in the tutorial is using I think Visual Studio 2013 Ultimate. When he types <% >%, there is intellisense.
I'm using Visual Studio 2013 Express for WEB, when I type
ViewData["CurrentTime"] = DateTime.Now.ToString();
The IDE doesn't recognize it and it prints this as a string. :(
Glenn you got confused between they way on how code blocks where annotated in aspx pages and how they are used in the Razor view engine nowadays.
You can see Razor in action right at the top of your View:
#{
ViewBag.Title = "Home";
}
And thats how you do it. The curly braces are optional, if you use a single expression, so in your case you could just write
<div>
This is my homepage! <br/>
TIME: #ViewData["CurrentTime"]
</div>
Scott Gu has written a pretty good article about the differences between the two systems: http://weblogs.asp.net/scottgu/introducing-razor
As a rule of thumb: If its an .aspx file, use <% %>. If it is a .cshtml or .vbhtml use #{ }
Related
I am trying to write this style of code from cassette using WebForms. Is this possible?
#{
var message = "Hello World!";
Bundles.AddInlineScript(
#<script>
if (someTest) {
alert('#message');
}
</script>);
}
I haven't managed to find an example of using methods with the Func<Object, Object> parameter in WebForms. Or is this because this only allowed by the Razor view engine?
<% Bundles.AddInlineScript("if (someTest) { ...") %>
I am attempting to implement a Captcha on a partial view of a page in my application. I have the captcha being refrenced through web.config as a control. I have used the GenericHandler and Class file from this forum post: http://forums.asp.net/t/1871186.aspx/1
How can I reference the user's input if i am using a simple input tag? Should I use an HtmlHelper instead?
<div class="captcha">
<rhcap:Captcha ID="Captcha1" runat="server"></rhcap:Captcha>
<input type="text" id="UserCaptchaText"><input/>
<%= Html.TextAreaFor(m => m.UserCaptcha) %>
</div>
<%if(Captcha1.Text != /* How can get the users input here?*/ ) {
//display error
}else{
//proceed
}%>
Use NuGet and install Recaptcha for .NET (supports MVC as well)
http://nuget.org/packages/RecaptchaNet/
Documentation is on the site:
http://recaptchanet.codeplex.com/
There are other captchas:
http://captchamvc.codeplex.com/
EDIT:
This project has moved to GitHub
https://github.com/tanveery/recaptcha-net
NuGet Google reCAPTCHA V2 for MVC 4 and 5
NuGet Package
Demo And Document
Web.config File in the appSettings section of your web.config file, add the keys as follows:
<appSettings>
<add name="reCaptchaPublicKey" value="Your site key" />
<add name="reCaptchaPrivateKey" value="Your secret key" />
</appSettings>
Add Recaptcha in your view.
#using reCAPTCHA.MVC
#using (Html.BeginForm())
{
#Html.Recaptcha()
#Html.ValidationMessage("ReCaptcha")
<input type="submit" value="Register" />
}
Verifying the user's response.
[HttpPost]
[CaptchaValidator]
public ActionResult Index(RegisterModel registerModel, bool captchaValid)
{
if (ModelState.IsValid)
{
}
return View(registerModel);
}
EDIT:
You should also add this in your head tag or you might see improper captcha
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
First off, it looks like you are mixing standard ASP.NET and ASP.NET MVC. If you want to do MVC, the standard way to do it is the Html.TextBoxFor() type of stuff, and then you handle the value of that in a controller action method rather than write something inline in the page. So you have something like this:
Page.aspx
<rhcap:Captcha ID="Captcha1" runat="server"></rhcap:Captcha>
<%= Html.TextBoxFor(m => m.UserCaptcha) %>
and then in:
SomeController.cs
[HttpGet]
public ActionResult Page()
{
// generate captcha code here
ControllerContext.HttpContext.Session["Captcha"] = captchaValue;
return View(new PageViewModel());
}
[HttpPost]
public ActionResult Page(PageViewModel model)
{
if (model.UserCaptcha == ControllerContext.HttpContext.Session["Captcha"])
{
// do valid captcha stuff
}
}
To take this to the next level would be to implement it in a FilterAttribute. But this should work for most uses.
I would recommend you to use Google reCAPTCHA, is the best and easy to implement plus it comes with the trust of Google.
Very very effective and easy to implement.
Read this article written by me on implementing Google reCAPTCHA in ASP.NET MVC
Thanks
I use this code to return an string from my action :
public ActionResult Index()
{
string List = "";
List = "<table><tr><td>Ali</td></tr></table>";
ViewData["List"] = List;
return View();
}
and this is my view :
<body>
<%: ViewData["List"] %>
</body>
but instead to create a table when i browse the page , i see that the string "<table><tr><td>Ali</td></tr></table>" wrote on it. I use the firebug and see its html code . but i saw something like this :
<table><tr><td>Ali</td></tr></table>
Is there any body out there to help me?
Thansk
Regards
This is because you use the HtmlEncode tag
Change the <%: to <%=
will be come
<body>
<%= ViewData["List"] %>
</body>
and do not forget to HtmlEncode your data only to avoid any injection.
In my code I am using a partial view (call it PV1)
<div id="div_1">
<% Html.Partial("PV1", Model); %>
</div>
and in that partial view I am using "Ajax.BeginForm" to redirect it to a particular action, hence it is doing so ...
using (Ajax.BeginForm("action1", "Forms", null, new AjaxOptions { UpdateTargetId = "div_1" }, new { id = "form1" }))
{
Response.write("I am here.");
}
public ActionResult action1(XYZ Model)
{
//
return PartialView("PV1", Model);
}
at the last line of action I am again calling the same partial 'PV1', hence it is doing this too ...
but when rendering the view it don't print or do the steps written with in partial view, it override them with and show nothing ...
Html.Partial actually returns the result of rendering the view, you want to do <%= Html.Partial() %> or <% Html.RenderPartial(); %>
Html.Partial() returns the Html and thusly must be output on the page via <%= %> and Html.RenderPartial() uses Response.Write to output onto the page and can be used with <% %>.
This is not what you would use Ajax.BeginForm for. That helper is used to create actual <form> tags that will later be submitted to the server using MVC's unobtrusive ajax (so you still need some kind of a trigger action - a button, javascript - anything that submits the form).
I'm am not very clear on what you're trying to achieve. If you want to load a partial view with ajax, I would suggest using something like jQuery's ajax load method.
i have aspx page which has following js function which is called on button click
<input type="button" onclick="calltemp1()" value="Temp1"/>
<script type="text/javascript">
function calltemp1() {
$("#Renderthisdiv").load("/Views/Templates/_Temp1.ascx");
}
</script>
my _Temp1.ascx page renders another page Temp1.ascx
my _Temp1.ascx contains
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<div>
<%Html.RenderPartial("/Views/Templates/Temp1.ascx"); %>
</div>
when i run the program i get the JavaScript runtime error saying "object expected"
please help me to solve this issue
Your JavaScript call is going to make another trip through the MVC Pipeline. So it will hit routing, a controller, and then a view. Your JavaScript should not try to hit the ascx file directly, but a route that maps to a controller that renders the view.
Your JS should look like this (note this is using a root relative URL, you may have to adjust):
$("#Renderthisdiv").load("/template/temp1");
Alternately, you can use an HTML helper to get the URL, but the JS will have to be in your view:
$("#Renderthisdiv").load("<%= Html.Action("temp1", "template") %>");
That URL will hit the Temp1 action on the TemplateController
public class TemplateController : Controller {
public ViewResult Temp1() {
return View("Temp1");
}
}
Just add the appropriate action to your controller so you can use jQuery to render it:
public class TemplateController : Controller {
public ViewResult Temp1() {
return View("_Temp1")
}
}