I'm new to MVC and I'm implementing the Nerd Dinner MVC sample app in MS MVC2. I'm on step 10, "Ajax enabling RSVPs accepts". I've added the new RSVP controller and added the Register action method like so:
public class RSVPController : Controller
{
DinnerRepository dinnerRepository = new DinnerRepository();
//
// AJAX: /Dinners/RSVPForEvent/1
[Authorize, AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(int id) {
Dinner dinner = dinnerRepository.GetDinner(id);
if (!dinner.IsUserRegistered(User.Identity.Name)) {
RSVP rsvp = new RSVP();
rsvp.AttendeeName = User.Identity.Name;
dinner.RSVPs.Add(rsvp);
dinnerRepository.Save();
}
return Content("Thanks - we'll see you there!");
}
}
I added the references to both Ajax script libraries and added the code below to the Details view as described in the article:
<div id="rsvpmsg">
<% if(Request.IsAuthenticated) { %>
<% if(Model.IsUserRegistered(Context.User.Identity.Name)) { %>
<p>You are registred for this event!</p>
<% } else { %>
<%= Ajax.ActionLink( "RSVP for this event",
"Register", "RSVP",
new { id=Model.DinnerID },
new AjaxOptions { UpdateTargetId="rsvpmsg"}) %>
<% } %>
<% } else { %>
Logon to RSVP for this event.
<% } %>
</div>
When I click the "RSVP for this event" link I get a 404 eror saying the resource cannot be found:
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /NerdDinner/RSVP/Register/24
Version Information: Microsoft .NET Framework Version:2.0.50727.4200; ASP.NET Version:2.0.50727.4205
When I step into the code it is finding the Register action method correctly. After playing around with it I removed the "AcceptVerbs(HttpVerbs.Post)" from the constraint on the Register method, and it then worked. However it didn't reload the page it just displayed the "Thanks - we'll see you there" message on a new blank page. Looking at the html in the details page there is no Form submit taking place, so I'm wondering does the Ajax code need something more to make the call a Post? Is there a known issue with this part of the Nerd Dinner app? I think the app was written in MVC1 and I'm using MVC2 - does this make a diference?
TIA,
Ciaran
The PDF tutorial (versus the online HTML version) has typographic ANSI quote characters (0x94) rather than ASCII (0x22) in the HTML block of script elements. The correct block is shown below with all of the quote characters replaced.
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
Visual Studio will mark the JavaScript source files with the Warning green squiggles ("File not found") but not the type attributes so you may notice and correct the problem only for the source files. However, the type attributes will still be malformed and this will cause the scripts not to be loaded correctly in the browser.
Using the Chrome developer tools, I noticed that the scripts were not listed as Resources for the Details HTML page. Correcting the quote characters for the type attributes allowed the Register action to work as documented in the tutorial with no changes.
This portion of your action explains why you just get the "see you there" message:
return Content("Thanks - we'll see you there!");
That's all that's being returned.
The reason you were getting a 404 to begin with is the use of an actionlink:
Ajax.ActionLink(...
That will create a URL link, a GET not a POST, and the AcceptVerbs(HttpVerbs.Post) would have forced no match. You should submit a form to do a post:
using (Ajax.BeginForm("Controller", "Action", new AjaxOptions { UpdateTargetId = "f1" } )) { %>
<div id="f1">
<!-- form fields here -->
<input type="submit" />
</div>
<% } %>
As an additional comment to debugging issues with this problem, being a Java/JSF developer, I ran into a hard lesson that
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript" />
and
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
are processed differently. The first not working at all and the second working correctly.
This is the Details.cshtml used in MVC3. The problem with redirecting using GET, and not POST is similar.
<div id="rsvpmsg">
#if (Request.IsAuthenticated)
{
if (Model.IsUserRegistered(Context.User.Identity.Name))
{
<p>
You are registered for this event</p>
}
else
{
#Ajax.ActionLink("RSVP for this event",
"Register",
"RSVP",
new { id = Model.DinnerID },
new AjaxOptions { UpdateTargetId = "rsvpmsg", HttpMethod = "Post" })
}
}
else
{
<p>
Logon to RSVP for this event.</p>
}
</div>
#section JavaScript
{
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>;
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>;
}
Ok, so previously i have mentioned that i had the same problem, and it comes from the fact that MVC 3 uses unobtrusive JavaScript.
To make this work, you have 2 solutions, one is to disable Unobtrusive Javascript in your webconfig file:
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Just set it to false, and during page build, javascript generated for the Action link will be normal inline javascript, that works fine, and results with something like this in HTML:
<a onclick="Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event),
{ insertionMode: Sys.Mvc.InsertionMode.replace, httpMethod: 'Post', updateTargetId: 'rsvpmsg' });" href="/RSVP/Register/13">RSVP for this event</a>
Second solution is more to my liking and it is just as simple. You just have to include additional javascript source file in your header:
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
#RenderSection("JavaScript",required:false)
</head>
The resulting javascript generated is unobtrusive, and results with this in HTML:
RSVP for this event
In both cases the resulting functionality is the same, and the second solution is "more in spirit" of new MVC 3.
Just in case it helps someone else, i had the problem using MVC 3 and it was because I had linked to the MS AJAX libraries and MVC 3 actually uses jQuery by default so I just needed to uncomment the links in my master page and it was fine.
To make an http post with Ajax.ActionLink , you'd have to do e.g. new AjaxOptions { UpdateTargetId="rsvpmsg",HttpMethod="POST"}
if you include those two in your site.master, it should be fine
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
I was trying to convert to MVC3/Razor as I worked through this example. I've been stuck on this exact same issue for at least 24 hours now...exact same symptoms. I tried everything on this page that I could understand or thought was relevant.
I didn't have the unobtrusive javascript mention in my web.config and was considering adding it with the "false" value thinking "true" might be the default. However, I was thinking it might screw something else up (among who knows what else).
I found the following tid-bit over on the wrox forum. If I add the following line of code to the second line of my RSVPStatus.cshtml partial view:
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
Everything works as intended. I know Zak mentioned that line of code above (and a bunch of other stuff that lead me in the right direction), but I was using the partial view and haven't seen a head tag since I started messing with MVC. I know it's probably there somewhere, but all the smoke and mirrors of what is MS programming now, makes it harder to dissect and I probably would have gone down Zak's path at some point. So, +1 for him.
Anyway, hope this helps someone save a day.
Related
MVC4 Internet project
I'm using Ajax.BeginForm to do a Postback with validation and it posts back the entire page rather than just the UpdateTargetID. I've looked at other posts on SO and haven't found the answer. I've built a new MVC4 Internet project just for testing (VS 2012 has been updated with 'ASP.NET and Web Tools 2012.2').
Here's my code
Controller
public ActionResult Index()
{
var vM = _db.Students.FirstOrDefault(); return View(vM);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(Student vM)
{
if (ModelState.IsValid)
{ //code if Model valid
return Json(new { url = Url.Action("About", "Controller") });
}
ModelState.AddModelError(string.Empty, "AJAX Post");
return PartialView("Index", vM);
}
View
#model AJAX_Test.Models.Student
#{ ViewBag.Title = "Student"; }
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript"> var onSuccess = function (result)
{
if (result.url) { window.location.href = result.url; }
}
// when server returns JSON object containing an url property redirect the browser </script>
<h1>#ViewBag.Title</h1>
<div id="IDXForm">
#using (Ajax.BeginForm("Index", new AjaxOptions() { UpdateTargetId = "IDXForm", OnSuccess = "onSuccess", HttpMethod = "Post" }))
{
#Html.AntiForgeryToken() #Html.ValidationSummary(true)
<span>#Html.EditorFor(m => m.FirstName) #Model.EnrollmentDate.ToShortDateString()</span> <input type="submit" value="Submit" />
}
</div>
The initial view is:
After Submittal:
Source code for body after submittal:
<div id="body">
<section class="content-wrapper main-content clear-fix">
<script src="/Scripts/jquery-1.8.2.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript"> var onSuccess = function (result) { if (result.url) { window.location.href = result.url; } }
// when server returns JSON object containing an url property redirect the browser </script>
<h1>Student</h1>
<div id="IDXForm">
<form action="/" data-ajax="true" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-success="onSuccess" data-ajax-update="#IDXForm" id="form0" method="post"><input name="__RequestVerificationToken" type="hidden" value="vkCszJu-fKT6zUr5ys2StOTPF6a9pZdj5k1MyaAZKo8MPweS53dUuni0C9B17NjL_GVydHa7-jI1H0F9HrYEdKxeCWq9mCeER3ebaZYLxIs1" /><span><input class="text-box single-line" id="FirstName" name="FirstName" type="text" value="Carson" /> 9/1/2005</span> <input type="submit" value="Submit" />
</form></div>
Can anyone see what is wrong with my code?
Thank you.
A couple of things that come to mind that might be causing this behavior:
In your question you have shown your bundle registrations but have you actually included them in your view or Layout? Make sure that in your view or layout you have first included jquery.js and then jquery.unobtrusive-ajax.js (in that order):
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
The jquery.unobtrusive-ajax.js script is not compatible with jquery 1.9 and later because it relies on the .live() which has been removed in jQuery 1.9. So if for some reason you have upgraded your jQuery version to 1.9 or later that won't work. You should downgrade.
In your onSuccess callback you are redirecting to an url if the controller action returns a JSON. Have you verified that this is not the case? Because when a redirect happens using the window.location.href it's pretty normal that you get a full page reload and not a partial update
In all cases use a javascript debugging tool to see what exactly is happening. If you are using Firefox, then you could use FireBug. If you are using Google Chrome, you could use the Chrome Developer Toolbar. Look at the console for potential javascript errors you might have. Look at the network tab to see whether all javascripts are successfully loaded and you don't have 404 errors. Learn how to debug your javascript code with a tool. You will be surprised how much information about potential issues you might have with your code those tools will provide you.
The contents of the UpdateTargetID must be in a partial view and that partial view needs to be called from the Controller Post Action. Darin answered me through e-mail (thank you Darin). You need to use a parital view. I've tried to update his answer twice and the moderators have not done it or provided an explanation why so I'm posting my own answer for others benefit.
_MyForm View:
#model AJAX_Test.Models.Student
#using (Ajax.BeginForm("Index", new AjaxOptions { UpdateTargetId = "IDXForm", OnSuccess = "onSuccess" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<span>
#Html.EditorFor(m => m.FirstName) #Model.EnrollmentDate.ToShortDateString()
</span>
<input type="submit" value="Submit" />
}
Main View :
<div id="IDXForm">
#Html.Partial("_MyForm")
</div>
Controller Post Action:
ModelState.AddModelError(string.Empty, "AJAX Post");
return PartialView("_MyForm", vM);
use:<script src="../Scripts/jquery.unobtrusive-ajax.js"></script>
This JS is what makes Ajax work.
Couple of other things to note.
jquery.unobtrusive-ajax.js now supports JQuery 1.9. I have installed jquery.unobtrusive-ajax.js version 3.0.0 and it is working with JQuery 1.9
2. Make sure all the div tages are closed properly, including the view which contains the Ajax.BeginForm and the main view. Also if you have #Html.Raw() in the main view or inside the view which contains Ajax.BeginForm be cautious about that too.
Posting here to save one day of head scratching.
make sure you have your bundles config include this
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
At a minimum, you need these two includes:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
And if that still does not help, check in web.config and make sure unobtrusive is enabled:
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
And if that still has no effect, make sure unobtrusive js files are compatible with current jQuery version, whatever version of jQuery you are using, which can be found at a below URL:
http://www.nuget.org/packages?q=unobtrusive
I have the same problem as posted here
I have a <button> element that triggers "A potentially dangerous request.form value..." error in asp.net MVC. For instance:
<button type="submit" name="logon" value="ok">Confirm</button>
<button type="submit" name="cancel" value="ok">Cancel</button>
And this javascript (with jquery UI 1.8.5)
<script type="text/javascript">
$(document).ready(function() {
$("button").button();
});
</script>
The issue is that I can't remove the name property (as the given solution in the link I posted) because I capture which button is pressed in the controller side this way:
public ActionResult Logon(FormCollection form, string logon, string cancel)
{
if (!string.IsNullOrEmpty(logon))
{
DoLogon();
}
if (!string.IsNullOrEmpty(cancel))
{
Cancel();
}
//etc
}
Is there any workaround for this? Thanks. Note that I don't have this problem in IE8 or firefox.
Have you seen this?
Cause
The .NET framework is throwing up an error because it detected something
in the entered text which looks like an HTML statement. The text doesn't
need to contain valid HTML, just anything with opening and closing
angled brackets ("<...>").
The solution proposed there is to disable the request validation on the server-side:
<pages validateRequest="false" />
Be sure to read through the warnings and explanations as well.
I'm trying to pass the header object here:
<%=FileUtil.AddStylesheetToHeader(Header, "UsedItems.css") %>
In my Master page I have a <head runat="server">. And my aspx page definitely has a reference to my MasterPageFile in the page directive at the top of my MVC based .aspx.
I also have an import statement the namespace that the FileUtil class resides in :
<%# Import Namespace="xxxx.Web.Utilities" %>
In standard ASP.NET you could reference the header with this.Header but in MVC I'm not able to do this...or I'm missing some kind of Imports or something.
for some reason though at runtime, with that call to AddStylesheetToHeader, I get the following error:
The best overloaded method match for 'System.IO.TextWriter.Write(char)' has some invalid arguments.
I'm not sure why it's looking at a .NET type as I know when I mouseover my FileUtil at compile time it's definitely referencing xxxx.Web.Utilities.FileUtil.
In that method I'm using HtmlLink styleSheet = new HtmlLink(); I may not be able to use this as it's an ASP.NET Web control? Here's that method:
public static void AddStylesheetToHeader(HtmlHead header, string cssFilename)
{
HtmlLink styleSheet = new HtmlLink();
styleSheet.Href = "content/css/" + cssFilename;
styleSheet.Attributes.Add("rel", "stylesheet");
styleSheet.Attributes.Add("type", "text/css");
header.Controls.Add(styleSheet);
}
I don't think I can use conrols that stem from System.Web.Controls since this is an ASP.NET application? If so, the how can I add a control to the header controls collection? Would I need to do this differently in MVC?
There may be a way to do it the way you're attempting, but it's more common in ASP.NET MVC to create a content placeholder in the <head> rather than accessing it programmatically. For example, your master view could look something like this:
<html>
<head>
<asp:ContentPlaceHolder ID="HeadContent" runat="server" />
</head>
</html>
And your view could look like this:
<asp:Content runat="server" ContentPlaceHolderID="HeadContent">
<link href="/content/css/UsedItems.css" rel="Stylesheet" type="text/css" />
</asp:Content>
have you tried this.Request.Header?
You can use JavaScript to dynamically add content to your HEAD section as shown in the code below:
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("head").append("<link href='Content/Site.css' rel='stylesheet' type='text/css' />");
});
</script>
I'm trying to auto-save a selection in a dropdown (ASP.NET, MVC, VB), but it's not behaving as expected. Here's the dummy action in the controller:
<AcceptVerbs(HttpVerbs.Post)> _
Function TestAction(ByVal id As Integer) As ActionResult
Return Content(id)
End Function
and the HTML:
<script type="text/javascript" src='<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>'></script>
<script type="text/javascript" src='<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>'></script>
<% Using Ajax.BeginForm("TestAction", New AjaxOptions With {.UpdateTargetId = "test"})%>
<%=Html.Hidden("id", 123)%>
<%=Html.DropDownList("actions", Nothing, New With {.onchange = "this.form.submit();"})%>
<input type="submit" value="Submit" />
<span id="test"></span>
<% End Using%>
The Submit button works as expected - the span is populated with "123". The dropdown on the other hand opens a new page with nothing but "123" on it. Why "this.form.submit()" not doing the same thing as the Submit button? Is there a different call I should make to emulate the Submit button?
this.form.submit does not run the form.onsubmit event. Pressing the submit button, on the other hand, does. That, combined with the HTML that Ajax.BeginForm generates, explains why the two behave differently. As for how to make your event do the same thing as pressing the submit button, look at the HTML in the linked article:
Sys.Mvc.AsyncForm.handleSubmit(
this,
new Sys.UI.DomEvent(event),
{
insertionMode: Sys.Mvc.InsertionMode.replace,
updateTargetId: 'test'
});
I know this is old, but there is a new (and better) way to do this.
Instead of doing using javascript, use jQuery. Just had this issue and it worked great.
this.form.submit() <---- Javascript
$("form").submit() <---- jQuery
I can't seem to get any client side validation working on a MVC 2 RC app.
My model has the following:
public class ExampleModel
{
[Required(ErrorMessage="Test1 is required")]
[DisplayName("Test1")]
public string Test1 { get; set; }
[Required(ErrorMessage="Test2 is required")]
[DisplayName("Test2")]
public string Test2 { get; set; }
}
My view has the following code:
<% Html.EnableClientValidation(); %>
<%= Html.ValidationSummary(true, "Test was unsuccessful.") %>
<% using (Html.BeginForm()) { %>
<div>
<div class="editor-label">Test1:</div>
<div class="editor-field">
<%= Html.TextBoxFor(m => m.Test1) %>
<%= Html.ValidationMessageFor(m => m.Test1) %>
</div>
<div class="editor-label">Test2:</div>
<div class="editor-field">
<%= Html.TextBoxFor(m => m.Test2) %>
<%= Html.ValidationMessageFor(m => m.Test2) %>
</div>
<p>
<input type="submit" value="Test" />
</p>
</div>
I leave both fields blank and click the Test button and it goes right to the controller's post handler with no client side validation happening. I am not sure what I am missing.
I have the following javascript also included in the view (not sure if I need it all):
<link href="../../Scripts/jquery-1.3.2.min.js" type="text/javascript" />
<link href="../../Scripts/jquery.validate.min.js" type="text/javascript" />
<link href="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript" />
Any ideas what I am doing wrong. I feel like I am missing something simple and the documentation for MVC 2 is sparse.
Edit: I have added the link:
<link href="../../Scripts/MicrosoftMvcJQueryValidation.js" type="text/javascript" />
And I have included the file in my project which I had to download from on of the links in the answers. Still not working at all. Any other ideas?
Edit: I am using Visual Studio 2008 with MVC 2 RC (not beta) and I am looking for any downloadable or posted examples of client-side validation working with the RC release.
When you update project from MVC 2 Beta, use: /src/MvcFutures/MicrosoftMvcJQueryValidation.js from MVC 2 RC Source Code Package (link). Older Beta version do not work correctly with jquery.validation in RC. Needed javascript files are:
<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript" />
<script src="/Scripts/jquery.validate.min-vsdoc.js" type="text/javascript" />
<script src="/Scripts/MicrosoftMvcJQueryValidation.js" type="text/javascript" />
Right version of MicrosoftMvcJQueryValidation.js contains this $(document).ready() function:
// need to wait for the document to signal that it is ready
$(document).ready(function() {
var allFormOptions = window.mvcClientValidationMetadata;
if (allFormOptions) {
while (allFormOptions.length > 0) {
var thisFormOptions = allFormOptions.pop();
__MVC_EnableClientValidation(thisFormOptions);
}
}
});
at the end of file (in RC release).
Ok I figured this out... and it is 100% my fault. Although, a couple of the posts included some information that I did need also.
The main problem, which I am suprised no one noticed, was my HTML to include the scripts... look up at my post and see if you can see the problem.
I was using a <link href=... tag instead of the proper <script src=... tag. Totally my fault as I had quickly cut and pasted the CSS link without thinking and just changed the type and file. Duh!!!
Anyways the correct links required are:
<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcJQueryValidation.js" type="text/javascript"></script>
Everything works then. You definately do need to include the 'MicrosoftMvcJQueryValidation.js' file from the futures project so I am upvoted all the posts that mentioned that.
Out of the box though that file is NOT included. If your not worried about using JQuery then you can just use the following includes to use the Microsoft implementation which will work out of the box with the RC:
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
I hope I can save at least one person some grief... I still can't believe how I could have screwed up the include and not noticed it for sooooo long.
Thanks again for all your help.
You have to include MicrosoftMvcJQueryValidation.js file :
<link href="MicrosoftMvcJQueryValidation.js" type="text/javascript" />
Check this: Where is the right version of MicrosoftMvcJQueryValidation.js for MVC 2 beta 2?
Next just put Html.EnableClientValidation(); somewhere in the View page.
It must be before the first form you want to client-side validate. I prefer Site.Master page.
Working on ASP.NET MVC 2 RC.
Are you sure you included the correct JS files? Because in Phill Haack's post it has MicrosoftMvcJQueryValidation.js attached instead of MicrosoftMvcValidation.js.
He also sets the ClientValidationFunction property in the view :
<% ViewContext.FormContext.ClientValidationFunction
= "EnableClientValidation"; %>
Though that was not RC, but Beta.
The default (and only supported by Microsoft) validation system in the ASP.NET MVC 2 Release Candidate does not use jQuery Validate. Instead, it uses a new validation system that exists entirely in MicrosoftMvcValidation.js (though you do also need to include MicrosoftAjax.js).
If you want to use the jQuery Validate library, it is included as part of the ASP.NET MVC Futures project (available here), which is a separate download, and has its own adapter script file.
Also, regarding the Html.ValidationSummary() helper, I believe it needs to be included inside the form if you want it to have the new client-side functionality. It will still work if it's outside of the form, but it will only work server-side.