ValidateAntiForgeryToken failing with jQuery ajax form submission - asp.net-mvc

I have an HTML form, to which I dynamically add a text field and perform a POST request for that form via jQuery to an ASP.NET MVC controller.
If I invoke the POST request without the ValidateAntiForgeryToken attribute on the controller action, it works fine. But, when I add the ValidateAntiForgeryToken attribute to the action I get the following exception:
"A required anti-forgery token was not supplied or was invalid."
Does anyone any ideas as to why this might be?
One point of note is that the token id in the cookie appears to be completely different to the token rendered in the form. Why might these be different?
The action:
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public string MyAction(Guid id, Dto dto)
{
//return JSON;
}
The form (as rendered):
<form id="slider" class="fc" method="post" action="/controller/myaction/" name="tabEdit">
<span id="slider_previous" class="sprite" tabindex="0" title="foo">Previous</span>
<input type="hidden" value="mzyg7UWQrHwafoSuoJBvwfraQEtCTAmM9QHYeyMSrAHFHG10BNXM+I2yNgz8zQ8yu/E43eF3yMuHX7YIQwmK3Q==" name="__RequestVerificationToken"/>
<div id="sliderWrap" style="width: 31.243%;">
<ul class="sliderList">
<li id="ID_3d031daf-a7f9-46f2-b4b9-7c9fc6560e3d">
</li>
<li id="ID_78b61634-d88a-4f33-8e48-e0655ad8a958" class="current">
<input class="sliderInput" type="text" value="" name="Bar"/>
<a class="sprite" href="/a/b/78b61634-d88a-4f33-8e48-e0655ad8a958">Delete</a>
</li>
</ul>
</div>
<span id="slider_addNew" class="sprite" tabindex="0" title="Add new">New</span>
<span id="slider_next" class="sprite" tabindex="0" title="See next">Next</span>
</form>
The original view rendering the anti-forgery token:
<form id="slider" class="fc" method="post" action="/controller/myaction/" name="tabEdit">
<%=Html.AntiForgeryToken(OurNamespace.MVC.Constants.SaltValue) %>
<ul class="noJs">
<!-- etc -->
</ul>
</form>

You are specifying a custom salt when you generate your AntiForgeryToken, you need to provide this salt to the ValidateAntiForgeryToken attribute as well.
[ValidateAntiForgeryToken(Salt=OurNamespace.MVC.Constants.SaltValue)]

Related

I want to POST the content of a uib-timepicker angular-ui bootstrap tag

I would like to let the user pick a time using a uib-timepicker tag and POST the result to my server (with a submit button for example).
<form class="simple_form vertical_form"
data-type="json" id="my_form"
action="url_to_post"
accept-charset="utf8"
data-remote="true"
method="post">
<div class="field">
<uib-timepicker
name="my_time"
ng-model="event.my_model"
hour-step="1"
minute-step="15"
show-meridian="true">
</uib-timepicker>
</div>
<div>
<input type="submit" value="Validate" class="btn btn-success">
</div>
</form>
But when I check to content of the POST method it is empty (I don't get the "my_time" key as I would expect. I guess it is because a "uib-timepicker" does not exactly work as an input field. But I feel like there must be a way to POST the content of that tag.
Thanks for helping!
I solved this issue by adding hidden input elements with binding to the time picker:
<uib-timepicker ng-model="ServiceRestoredTime" name="ServiceRestoredTime" ng-change="changed()" hour-step="hstep" minute-step="mstep" show-meridian="false" show-spinners="false"></uib-timepicker>
<input type="hidden" name="ServiceRestoredTimeParam" value="{{ServiceRestoredTime | date:'HH:mm' }}">

Login MVC redirect to another page

I have a log-in page. When the user hits the log-in button the button will calla another action method. that action method will have two parameter. the user provided userid and password. then it do some validation and redirect to another action method according to the outcome. I am struggling with there. i guess this is pretty simple. i am new to MVC. Any help would be appriciated.
View
<div class="container-fluid">
<div class="starter-template">
<h1>Policy Assessment Tool</h1>
<p class="lead">Are You Following Right?</p>
<button type="button" class="btn btn-primary btn-lg" onclick="location.href='#Url.Action("Create","UserDatas")'">Register for a An Account</button>
<h3><strong>OR</strong></h3>
</div>
<div class="row">
<form class="form-signin" role="form" method="post">
<div class="col-lg-4"></div>
<div class="col-lg-4">
<h2 class="form-signin-heading">Please Sign-In to Continue</h2>
<div class="input-group">
<input type="text" name="input_domain_id" class="form-control text-center" placeholder="Domain ID" autofocus required>
<input type="password" name="input_domain_password" class="form-control text-center" placeholder="Domain Password" required>
<div class="col-lg-12">
<p><button class="btn btn-lg btn-primary btn-block" type="submit" onclick="location.href='#Url.Action("Verify_Login", "Ldap_Login_Verify")'">Login</button></p>
</div>
</div><!-- /input-group -->
</div><!-- /.col-lg-4 -->
<div class="col-lg-4"></div>
</form>
</div><!-- /.row -->
</div>
Controller
[HttpPost]
public ActionResult Verify_Login(string input_domain_id, string input_domain_password)
//Log-in Logic
return View("Success")
Instead of using form tag use Html.BeginForm HtmlHelper and pass Model from Controller to View for the best practice. Here is link for you to get Getting Started With MVC5.
Based on the mark up above you need not worry about it, When the form is posted the values will get bound to the parameters of the action method, As the parameter names are similar to the form field names.
The above concept is called model binding. The below two links should give you a good idea on the same.
http://www.codeproject.com/Articles/710776/Introduction-to-ASP-NET-MVC-Model-Binding-An-Absol
http://dotnetslackers.com/articles/aspnet/Understanding-ASP-NET-MVC-Model-Binding.aspx
I have tried to compile a simple example below.
Lets assume there is a view like below.
#model string
#{
ViewBag.Title = "Injection";
}
<h2>Injection</h2>
#using(Html.BeginForm())
{
<div id="formDetails">
#Html.TextBox("UserName")
</div>
<div>
<input type="submit" id="btnTest" value="Click Me" />
</div>
}
The Action method for the same would be like
[HttpPost]
public ActionResult Injection(string UserName)
{
return View("Injection");
}
So when i click on the submit button, The form is posted , Since the ViewName is injection, and there is a corresponding action method called injection it will automatically hit that action method. Since the parameter name of the method and field is the same, What ever value is there in the username textbox will get automatically bound to the method parameter.

unable to display the validation messages from #Html.ValidationSummary() in MVC view

I have a fairly simple form created in a partial view and loading the form on a jquery dialog. The view is tightly bound to a model. When the user clicks on the submit button with out entering any inputs, I need to show the validation messages.
<div>
<form method="post" enctype="multipart/form-data" id="ssimForm" action="Home/ProcessUploadedFile"
onsubmit="return false;">
<div>
<h3>
Select the file to be uploaded :</h3>
<span>
<input type="file" name="UploadFileName" id="UploadFileName" /></span>
</div>
<div>
<h3>
Select the date range :</h3>
<span class="uslabel">From Date(MM/dd/yyyy): </span>
<input class="usdate" id="usfromdate" name="StartDate" type="date" />
<span class="uslabel">To Date(MM/dd/yyyy): </span>
<input class="usdate" id="ustodate" name="EndDate" type="date" />
</div>
<div>
<br />
<input type="submit" id="submitButton" name="submitButton" value="Process File" />
</div>
#Html.ValidationSummary()
<div class="message-success">
<span>#ViewBag.Confirmation</span>
</div>
<div class="message-error">
<span>#ViewBag.Error</span>
</div>
</form>
</div>
Now comes the actual problem. when I submit the form I am able to see the validationSummary object populated with the messages, but they are not getting rendered on the screen.
I am able to see the messages if I replace the content of the dialog with the response from the jquery ajax call, that fetches the entire view from the server side. I do not want to take this approach as I beleive this is not the correct way to return validation summary in MVC.
Am I missing something? Any help is appreciated.
I don't know why you don't have the #using (Html.BeginForm()) { } block.
Here is my blog post for a quick and easy way to set up Validation Summary + Unobtrusive Validation for MVC3+.
http://geekswithblogs.net/stun/archive/2011/01/28/aspnet-mvc-3-client-side-validation-summary-with-jquery-validation-unobtrusive-javascript.aspx

Why am I getting this Javascript HIERARCHY_REQUEST_ERR with jQuery Mobile and Razor?

Dazed and confused here... The field in question is a boolean, and I want the UI to be a checkbox (or a yes/no or on/off jQuery slider). Each time I try to add in this checkbox input, I end up getting a
Microsoft JScript runtime error: DOM Exception: HIERARCHY_REQUEST_ERR (3)
error.
Here's the HTML+Razor
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>End Game:</legend>
#Html.TextBoxFor(model => model.HandicapSession.WinByTwo, new { #type="checkbox" })
<label for="WinByTwo">Win By Two?</label>
</fieldset>
</div>
Here's the generated HTML:
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>End Game:</legend>
<input data-val="true" data-val-required="The WinByTwo field is required." id="HandicapSession_WinByTwo" name="HandicapSession.WinByTwo" type="checkbox" value="False" />
<label for="WinByTwo">Win By Two?</label>
</fieldset>
</div>
Apparently this error occurs when there are conflicting or overlapping id's as jQuery Mobile creates its checkbox widget
$.widget( "mobile.checkboxradio", $.mobile.widget, { ...etc...
But how do I use the HTML and/or razor to make a simple checkbox work in jQuery Mobile?
If the problem with jQuery Mobile really is duplicate names for the HTML tags, then you'll have to render your own input type=checkbox tag in HTML, as the ASP.NET MVC Html.CheckBoxFor helper method will render an input type=hidden tag with a duplicate name value. See this post for a discussion.
The hidden form tag is there because if you submit an unchecked checkbox to the server, the form value for that field isn't included. So a hidden input tag is included with value=false so that if the checkbox is unchecked, the value false is still submitted. The model binding process in MVC will filter out the duplicate form values for you, but if you're having a client-side problem with the duplicate name attributes, you'll have to render your own checkbox and label in HTML, then handle the fact that no value will be submitted for the HandicapSession.WinByTwo property when the box is unchecked. If no other property for HandicapSession is submitted, then that whole object will be null.
So, you can manually create the checkbox input and still load the checked and value attributes from your model, as desired, but you can run into model binding problems where the value for WinByTwo will still be false even when the box is checked.
Note also that the for attribute on your label doesn't match the ID of the checkbox in your sample. You need the full HandicapSession_WinByTwo.
The following manually creates the input tags:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.css" />
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.js"></script>
<div data-role="page">
<div data-role="content">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>End Game:</legend>
<input type="checkbox" id="HandicapSession_WinByTwo" name="HandicapSession.WinByTwo" #(Model.HandicapSession.WinByTwo ? "checked=checked" : "") value="#(Model.HandicapSession.WinByTwo.ToString().ToLower())" />
<label for="HandicapSession_WinByTwo">Win By Two?</label>
</fieldset>
</div>
</div>
</div>
The HTML output is as follows for a checked checkbox on load:
<div data-role="page">
<div data-role="content">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>End Game:</legend>
<input type="checkbox" id="HandicapSession_WinByTwo" name="HandicapSession.WinByTwo" checked=checked value="true" />
<label for="HandicapSession_WinByTwo">Win By Two?</label>
</fieldset>
</div>
</div>
</div>
The best would be just to use the MVC helper methods, so I'm not sure if you'd tried the following. The default Html.CheckBoxFor and Html.LabelFor helper methods work with jQuery Mobile 1.0a4.1 or 1.1.0 just fine. The following works for me:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.css" />
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.js"></script>
<div data-role="page">
<div data-role="content">
#using (Html.BeginForm())
{
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>End Game:</legend>
#Html.CheckBoxFor(m => m.HandicapSession.WinByTwo)
#Html.LabelFor(m => m.HandicapSession.WinByTwo, "Win By Two?")
<input type="submit" id="SubmitForm" value="submit" />
</fieldset>
</div>
}
</div>
</div>
This produces the HTML output:
<div data-role="page">
<div data-role="content">
<form action="/Mobile/Mobile" method="post">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>End Game:</legend>
<input checked="checked" data-val="true" data-val-required="The WinByTwo field is required." id="HandicapSession_WinByTwo" name="HandicapSession.WinByTwo" type="checkbox" value="true" />
<input name="HandicapSession.WinByTwo" type="hidden" value="false" />
<label for="HandicapSession_WinByTwo">Win By Two?</label>
<input type="submit" id="SubmitForm" value="submit" />
</fieldset>
</div>
</form>
</div>
</div>
Fix might be pretty simple.
Choice 1: Go scorched earth and turn off Ajax based navigation. This will ensure that unique IDs stay unique. This will ensure that you never encounter this issue again. Only downside is that you lose the pretty little transitions from page to page (someone call the whambulance). You can do this by setting up a global configuration script...
script src="jquery.js"
script src="custom-scripting.js"
script src="jquery-mobile.js"
inside that you'll override the ajax settings to disable them...
$(document).bind("mobileinit", function(){
$.mobile.ajaxEnabled = false;
});
Choice 2: Call pages that are going to require this uniqueness with a link that has an attribute of rel='external' or target='_black' which will accomplish the same thing without disabling all ajax based navigation. If you are reaching the page as a results of a form post, you can use data-ajax='false' on the form tag to accomplish a clean load.

asp mvc user controls

I want to write user control to sending email.
I write that control:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<form action="" method="post">
<div class="box">
<div class="box-header">
Rejestracja</div>
<div class="box-content">
<div>
Imię
</div>
<div>
<input name="firstname" type="text" />
</div>
<div>
Nazwisko
</div>
<div>
<input name="lastname" type="text" />
</div>
<div>
Email
</div>
<div>
<input name="email" type="text" />
</div>
<div>
Ulica nr domu mieszkania
</div>
<div>
<input name="street" type="text" />
</div>
</div>
<div class="box-info">
Wypełnij formularz rejestracyjny i dołącz do klubu Oriflame.
</div>
</div>
<div style="clear: both;">
</div>
</form>
And i put this control in masterpage:
<% Html.RenderPartial("Kontakt"); %>
That control named :kontakt.aspx" and it is in shared folder
My question is where i must write code with sending email. What action i myst set in controls form.
This control was be on all sites.
Regards
The form needs to post to a URL that is setup to route to a controller action. That could be the current page's Url or a different Url.
In your controller you want a method that accepts the form fields. This could be a FormCollection object or a strongly typed model who's properties map to the form names.
[HttpPost]
public ActionResult Foo(FormCollection form)
{
.. use the form collection to construct your email ...
}
If you're using a strongly typed view, rather than building the HTML inputs yourself you could do:
<%= Html.TextBoxFor(x => x.FirstName) %>
And in your controller action you can use the model rather than the FormCollection:
[HttpPost]
public ActionResult Foo(KontaktModel details)
{
.. use the details object to construct your email ...
}
I suggest taking a look through the tutorials at http://asp.net/mvc as well as doing the NerdDinner tutorial.
You have to create some sort of Controller that will receive form data. And you can send those emails from the server (from controller or whatever you chose to send it).
Write your email creation and sending code in a controller method. You'd then call it from this Kontakt partial view like this:
<% using (Html.BeginForm("SendMail", "Mail")) { %>
Where SendMail is the method, and Mail is the name of the controller.
public ActionResult SendMail()
{
//build your mail objects and send as needed.
return View();
}

Resources