I'm trying to make a method run once a user clicks a button on a page. I created a sample of code to test it but it doesn't work, though it may be because I'm using MessageBox.
<input id="upload-button" type="button" ondblclick="#ModController.ShowBox("Message");" value="Upload"/><br />
Here's the method I'm invoking.
public static DialogResult ShowBox(string message)
{
return MessageBox.Show(message);
}
Any idea on how I can make this function properly?
You could do something like this if your intent is to pass a message to the client and display a dialog:
In your view, add the following:
#using (Html.BeginForm("ShowBox","Home",FormMethod.Post, new { enctype = "multipart/form-data" })){
#Html.Hidden("message", "Your file has uploaded successfully.");
<input id="upload-button" type="submit" value="Click Me" />
<input id="file" name="file" type="file" value="Browse"/>
}
Then in your controller:
[HttpPost]
public ActionResult ShowBox(string message, HttpPostedFileBase file)
{
if (file == null || file.ContentLength == 0)
{
//override the message sent from the view
message = "You did not specify a valid file to upload";
}
else
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"));
file.SaveAs(path);
}
System.Text.StringBuilder response = new System.Text.StringBuilder();
response.Append("<script language='javascript' type='text/javascript'>");
response.Append(string.Format(" alert('{0}');", message));
response.Append(" var uploader = document.getElementById('upload-button'); ");
response.Append(" window.location.href = '/Home/Index/';");
response.Append("</script>");
return Content(response.ToString());
}
NOTE:
I think this approach is less than ideal. I'm pretty sure that returning JavaScript directly like this from the controller is probably some sort of an anti-pattern. In the least, it does not feel right, even thought it works just fine.
It looks like you're using a Razor template. If so, and you're using MVC, I don't think you're approaching this right. MVC doesn't work on an event system like ASP.NET. In MVC you make a requst to an ACtion method, usually with a URL in the form of {controller}/{action}, or something like that.
you have few options:
Setup a javascript event for the dblClick event, and perform an AJAX request to the server in the event handler.
Use #ActionLink() and style it to look like a button.
If you are using ASP.NET, there are certain POST parameters you can set before posting to the server, which will tell ASP.NET to run a certain event handler. However, if you're using ASP.NET, I'd recommend using web forms instead of Razor. I've never used Razor with ASP.NET myself, but I don't think the two technologies Jive very well.
Related
I am trying to develop a website, the website got a pop-up modal which allows the user to subscribe to our latest promotion. In that input, we got a textbox to allow users to key in their email.
However, when we look at the HTML code, the HTTP POST URL is visible:
If someone is trying to use this URL, and spam HTTP POST requests (see below), unlimited entries can be created in the subscriber database table.
for (int a = 0; a < 999999; a++)
{
var values = new Dictionary<string, string>
{
{ "email", a+"#gmail.com" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
}
How can I prevent this from happening? We cannot put a capcha, since this is subscriber to our promotion.
Edit: Please note that a ANTI-forgery token will not work, because the hacker can download entire HTML string using GET, and get the value from the anti forgery token textbox and POST the value to the POST URL again, so it will not work and the same anti-forgery token can use multiple times, it is not secure.
You can choose one of the below option to implement what you are looking for.
1- Implement CAPTCHA/re-CAPTCHA, it will make sure that using any tool request can't be made. I understand that you don't want to use CAPTCHA, I still feel you should go with it, as it is the best approach to handle this type of scenarios.
2- IP Based restriction, lock submitting the request from one IP for some time.
3- Other option can be OTP (one time password), you can send the OTP to the email, and only after successful verification you can register the email.
Use AntiForgeryToken. Read more about Antiforgery Tokens here
In your form Razor View, Add an #Html.AntiForgeryToken() as a form field.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#*Rest of the form*#
}
In your Action Method use ValidateAntiForgeryTokenAttribute
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit( MyViewModel form)
{
if (ModelState.IsValid)
{
// Rest of ur code
}
}
I've been brought onto my first MVC and C# project so I appreciate any guidance.
I've created a new feature that checks to see if user has had security training when they log in. If they haven't, the user is directed to a training page where they simply agree/disagree to the rules. If the user agrees, login is completed. If user disagrees, he/she is logged off.
The issue that I have is that when I select the Agree/Disagree button in the training view, I get the following
It should route me to the homepage or logout the user.
Controller
public ActionResult UserSecurityTraining(int ID, string returnUrl)
{
// check if user already has taken training (e.g., is UserInfoID in UserSecurityTrainings table)
var accountUser = db.UserSecurityTraining.Where(x => x.UserInfoID == ID).Count();
// If user ID is not in UserSecurityTraining table...
if (accountUser == 0)
{
// prompt security training for user
return View("UserSecurityTraining");
}
// If user in UserSecurityTraining table...
if (accountUser > 0)
{
return RedirectToLocal(returnUrl);
}
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> UserSecurityTrainingConfirm(FormCollection form, UserSecurityTraining model)
{
if (ModelState.IsValid)
{
if (form["accept"] != null)
{
try
{
// if success button selected
//UserSecurityTraining user = db.UserSecurityTraining.Find(); //Create model object
//var user = new UserSecurityTraining { ID = 1, UserInfoID = 1, CreatedDt = 1 };
logger.Info("User has successfully completed training" + model.UserInfoID);
model.CreatedDt = DateTime.Now;
db.SaveChanges();
//return RedirectToAction("ChangePassword", "Manage");
}
catch (Exception e)
{
throw e;
}
return View("SecurityTrainingSuccess");
}
if(form["reject"] != null)
{
return RedirectToAction("Logoff", "Account");
}
}
return View("UserSecurityTraining");
}
View
#model ECHO.Models.UserSecurityTraining
#{
ViewBag.Title = "Security Training";
Layout = "~/Views/Shared/_LayoutNoSidebar.cshtml";
}
<!--<script src="~/Scripts/RequestAccess.js"></script>-->
<div class="container body-content">
<h2>#ViewBag.Title</h2>
<div class="row">
<div class="col-md-8">
#using (Html.BeginForm("UserSecurityTrainingConfirm", "Account", FormMethod.Post, new { role = "form" }))
{
<fieldset>
#Html.AntiForgeryToken()
Please view the following security training slides:<br><br>
[INSERT LINK TO SLIDES]<br><br>
Do you attest that you viewed, understood, and promise to follow the guidelines outlined in the security training?<br><br>
<input type="submit" id="accept" class="btn btn-default" value="Accept" />
<input type="submit" id="reject" class="btn btn-default" value="Reject" />
</fieldset>
}
</div><!--end col-md-8-->
</div><!--end row-->
</div><!-- end container -->
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I don't think you've provided enough of your code to properly diagnose this particular error. In general, this anti-forgery exception is due to a change in authentication status. When you call #Html.AntiForgeryToken() on a page, a cookie is set as well in the response with the token. Importantly, if the user is authenticated, then the user's identity is used to compose that token. Then, if that user's authentication status changes between when the cookie is set and when the form is posted to an action that validates that token, the token will no longer match. This can either be the user being authenticated after the cookie set or being logged out after the cookie is set. In other words, if the user is anonymous when the page loads, but becomes logged in before submitting the form, then it will still fail.
Again, I'm not seeing any code here that would obviously give rise to that situation, but we also don't have the full picture in terms of how the user is being logged in an taken to this view in the first place.
That said, there are some very clear errors that may or may not be causing this particular issue, but definitely will cause an issue at some point. First, your buttons do not have name attributes. Based on your action code, it appears as if you believe the id attribute will be what appears in your FormCollection, but that is not the case. You need to add name="accept" and name="reject", respectively, to the buttons for your current code to function.
Second, on the user successfully accepting, you should redirect to an action that loads the SecurityTrainingSuccess view, rather than return that view directly. This part of the PRG (Post-Redirect-Get) pattern and ensures that the submit is not replayed. Any and all post actions should redirect on success.
Third, at least out of the box, LogOff is going to be a post action, which means you can't redirect to it. Redirects are always via GET. You can technically make LogOff respond to GET as well as or instead of POST, but that's an anti-pattern. Atomic actions should always be handled by POST (or a more appropriate verb like PUT, DELETE, etc.), but never GET.
Finally, though minor, the use of FormCollection, in general, is discouraged. For a simple form like this, you can literally just bind your post as params:
public ActionResult UserSecurityTrainingConfirm(string accept, string reject, ...)
However, then it'd probably be more logical and foolproof to introduce a single boolean like:
public ActionResult UserSecurityTrainingConfirm(bool accepted, ...)
Then, your buttons could simply be:
<button type="submit" name="accepted" value="true" class="btn btn-default">Accept</button>
<button type="submit" name="accepted" value="false" class="btn btn-default">Reject</button>
This essentially makes them like radios. The one that is clicked submits its value, so the accepted param, then, will be true or false accordingly. Also, notice that I switched you to true button elements. The use of input for buttons is a bad practice, especially when you actually need it to submit a value, since the value and the display are inherently tied together. With a button element, you can post whatever you want and still have it labeled with whatever text you want, independently.
I am using MVC with PagedList in order to have a big table divided into multiple pages.
Now, in the web browser, this is what I see:
http://localhost:49370/Home/Pending?page=2
Which makes sense. However, when sending a request to the server, this is what the server receives: http://localhost:49370/Home/WhereAmI?_=1429091783507
This is a huge mess, and in turn it makes it impossible to redirect the user to specific pages in the list because I don't know what is the page the user is currently viewing !
Controller code:
public ActionResult Pending(int? page)
{
//I have a ViewModel, which is MaterialRequestModel
IEnumerable<MaterialRequestModel> model = DB.GATE_MaterialRequest
.Select(req => new MaterialRequestModel(req))
.ToList();
int pageNum = page ?? 1;
return View(model.ToPagedList(pageNum, ENTRIES_PER_PAGE));
}
View code:
#model IEnumerable<MaterialRequestModel>
<table>
//table stfuff
</table>
<div style="display: block;text-align: center">
#Html.PagedListPager((PagedList.IPagedList<MaterialRequestModel>)Model, page => Url.Action("Pending", new { page }), PagedListRenderOptions.ClassicPlusFirstAndLast)
</div>
Is this a limitation of MVC PagedList? Or am I missing something?
It happens that PagedList does not send this type of information to the server. Instead, if you want to know which page is being looked at, you have to use a custom model that has that information, and if you want to make a request usign ajax (the original objective here) you must using a special option:
#Html.PagedListPager(Model.requests, page => Url.Action("SearchTable", "Home",
new
{
employeesQuery = Model.query.employeesQuery, //your query here
pageNum = page
}
), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "tableAndPaginationDiv", OnComplete = "initiatePendingTableDisplay" }))
Admittedly this solution is poor at best. You can only have 1 option of the entire list (so if you are already using other options somewhere else you can forget it) and you have no control whatsoever on the request made, so customization is really not an option here unless you feel like hooking the calls.
Anyway, this is how I fixed it, hopefully it will help someone in the future!
What is the recommended way to handle "Nick / Email taken" AJAX validation in MVC that integrates nicely with validators provided by DataAnnotantion (#Html.ValidationMessageFor(model => model.Email))? I understand that I would probably have something like this:
<input id="email" onBlur="emailTaken();" onchanged="emailTaken();" />
<script type="text/javascript">
function emailTaken() {
var encodedEmail = enc($("#email").val());
$.getJSON("/Ajax/EmailTaken/" + encodedEmail, function (data) {
if (data.res) {
// all is OK
} else {
// TODO: Show Error?
}
});
}
</script>
I already know that on Server I can do ModelState.AddModelError and I am doing it... but I want to know what is recommended way for ClientSide validation? Do I need to invoke some method provided by jquery.validate.unobtrusive.js?
You would probably want to use Remote Validation for this. It's built-in, so you don't have to do any of your own javascript.
http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx
Please keep in mind that I'm rather new to how MVC, Json, jQuery, etc. works, so bear with me. I've been doing Web Forms for the past 5 years...
I'm working on validating a form within a Modal popup that uses a JsonResult method for posting the form data to the server. I wish I could have just loaded a Partial View in that popup and be done with it, but that's not an option.
Anyway, I have some code that was working yesterday, but after I did a pull / push with Git, something went a bit wrong with my validation. I do some basic validation with regular JavaScript before I pass anything to the server (required fields, correct data types, etc.), but some things, like making sure the name the user types in is unique, require me to go all the way to the business logic.
After poking around the internet, I discovered that if you want jQuery to recognize an error from a JsonResult in an AJAX request, you must send along a HTTP Status Code that is of an erroneous nature. I'm fairly certain it can be any number in the 400's or 500's and it should work...and it does...to a point.
What I would do is set the Status Code and Status Description using Response.StatusCode and Response.StatusDescription, then return the model. The jQuery would recognize an error, then it would display the error message I set in the status description. It all worked great.
Today, it seems that the only thing that makes it from my JsonResult in my controller to my jQuery is the Status Code. I've traced through the c# and everything seems to be set correctly, but I just can't seem to extract that custom Status Description I set.
Here is the code I have:
The Modal Popup
<fieldset id="SmtpServer_QueueCreate_Div">
#Form.HiddenID("SMTPServerId")
<div class="editor-label">
#Html.LabelFor(model => model.ServerName)
<br />
<input type="text" class="textfield wide-box" id="ServerName" name="ServerName" title="The display name of the Server" />
<br />
<span id="ServerNameValidation" style="color:Red;" />
</div>
<div class="editor-label">
<span id="GeneralSMTPServerValidation" style="color:Red;" />
</div>
<br />
<p>
<button type="submit" class="button2" onclick="onEmail_SmtpServerQueueCreateSubmit();">
Create SMTP Server</button>
<input id="btnCancelEmail_SmtpServerQueueCreate" type="button" value="Cancel" class="button"
onclick="Email_SmtpServerQueueCreateClose();" />
</p>
</fieldset>
The Controller
[HttpPost]
public virtual JsonResult _QueueCreate(string serverName)
{
Email_SmtpServerModel model = new Email_SmtpServerModel();
string errorMessage = "";
try
{
Email_SmtpServer dbESS = new Email_SmtpServer(ConnectionString);
model.SMTPServerId = System.Guid.NewGuid();
model.ServerName = serverName;
if (!dbESS.UniqueInsert(model, out errorMessage))
{
return Json(model);
}
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
Response.StatusCode = 500;
Response.StatusDescription = errorMessage;
return Json(model);
}
The jQuery Ajax Request
$.ajax({
type: 'POST',
data: { ServerName: serverName },
url: getBaseURL() + 'Email_SmtpServer/_QueueCreate/',
success: function (data) { onSuccess(data); },
error: function (xhr, status, error) {
$('#GeneralSMTPServerValidation').html(error);
}
});
Like I mentioned, yesterday, this was showing a nice message to the user informing them that the name they entered was not unique if it happened to exist. Now, all I'm getting is a "Internal Server Error" message...which is correct, as that's what I am sending along in my when I set my Status Code. However, like I mentioned, it no longer sees the custom Status Description I send along.
I've also tried setting it to some unused status code to see if that was the problem, but that simply shows nothing because it doesn't know what text to show.
Who knows? Maybe there's something now wrong with my code. Most likely it was a change made somewhere else, what that could be, I have no idea. Does anyone have any ideas on what could be going wrong?
If you need any more code, I'll try to provide it.
Thanks!
In your error callback, try using
xhr.statusText
Also, if you're using Visual Studio's webserver, you may not get the status text back.
http://forums.asp.net/post/4180034.aspx