Displaying error messages using C# with Razor - c#

I'm new to C# and am trying to add some simple server side validation to my site. I've tried to Google this, but information is a little thing on the ground.
So for instance, if I values inside of a form like such :
<table>
<tr>
<td>FredF</td>
<td>Fred Flintstone</td>
<td><input type="checkbox" name="userId" value="#user.UserId" /></td>
</tr>
<tr>
<td>BarneyR</td>
<td>Barney Rubble</td>
<td><input type="checkbox" name="userId" value="#user.UserId" /></td>
</tr>
<tr>
<td>WilmaF</td>
<td>Wilma Flintstone</td>
<td><input type="checkbox" name="userId" value="#user.UserId" /></td>
</tr>
</table>​
And I want to verify that the user has ticked a checkbox, and if they haven't, I want a message to be displayed saying they must check the box.
What is best practice for doing this?

Assuming you're using MVC, best practice for server-side is to use a ViewModel with your form that has an attribute specifying if the property is required or not.
So it would be something like
class User
{
[Required]
public bool IsChecked{get;set;}
}
Then in your Controller Post Action you check Model.IsValid and re-show the form if not.

That depends on many factors, like are you using a model, are you using jquery and do you have client side validation enabled.
Read this article:
http://www.codeproject.com/Articles/344292/ASP-NET-MVC3-Razor-With-JQuery-For-Beginners
http://www.asp.net/mvc/tutorials/overview/creating-a-mvc-3-application-with-razor-and-unobtrusive-javascript

Related

Updating model with Core 2.2

How do you handle the Id in a detail page with the newest ASP.NET Core 2.2 technology?
If I use a hiden field with the Id it gets passed when I click on save.
But when I comment it I wont get the Id.
<form asp-controller="Coach" asp-action="UpdateCoach" method="post">
#*<input asp-for="Coach.Id" type="hidden" />*#
<table class="table table-bordered table-condensed">
<tr>
<td>Naam:</td>
<td><input asp-for="Coach.CoachName" value="#Model.Coach.CoachName" /></td>
</tr>
<tr>
<td>Type coach:</td>
<td>
<select asp-for="Coach.CoachTypeId" asp-items="#(new SelectList(Model.CoachTypes,"Id", "CoachTypeDescription"))">
<option></option>
</select>
</td>
</tr>
<tr>
<td>Telefoon:</td>
<td><input asp-for="Coach.CoachPhone" value="#Model.Coach.CoachPhone" /></td>
</tr>
<tr>
<td>Email:</td>
<td><input asp-for="Coach.CoachEmail" value="#Model.Coach.CoachEmail" /></td>
</tr>
</table>
<input type="submit" value="Opslagen" class="btn btn-default" />
This is my Controller :
[HttpPost]
public async Task<IActionResult> UpdateCoach(CoachViewModel coachViewModel)
{
return Redirect("/Coach/Coach");
}
In coachViewModel I get all values expect the Id!
How do you handle the Id in a detail page
Assuming this is an "edit" page for an entity that already exists in a database, then your options include:
Store it in a hidden field so it's included in the POST.
Use it as a URI path parameter or querystring parameter
e.g. GET /users/{userId} and PSOT /users/{userId} or GET /users?userId={userId} and POST /users?userId={userId}
If the Id value can be determined from the current request (e.g. based on a User's security Claim or something in session-state) then use that.
If this is a page to define data for a new entity that doesn't exist yet (assuming you're using IDENTITY/AUTO_INCREMENT), then it doesn't matter because you'll be doing an INSERT operation anyway and you should have a separate URI path (and Controller Action) for this operation anyway (i.e. so your code doesn't expect nor require any entity identifier in this scenario).

how to perform the action when clicking the html submit button without using runat server

how to perform an action when i click the html submit button without using runat server. Where i have to write the code and what i have to write. Please help me. I have a below code:
<table>
<tr>
<td>Enter User Id</td>
<td><input type="text" id="txtUserId" name="userId"/></td>
</tr>
<tr>
<td>Enter Password</td>
<td><input type="password" id="txtPassword" name="password"/></td>
</tr>
<tr>
<td>
<input type="checkbox" id="chkRememberMe" />
<label for="chkRememberMe">Remember Me</label>
</td>
</tr>
<tr>
<td><input type="Submit" id="btnSubmit" value="Login" name="submitButton"/></td>
</tr>
</table>
I want to write logic in *aspx.cs file. Thank you.
Any http post of a page back to the server will trigger your codebehind to be executed, regardless of whether you have a runat="server" or not. You can detect this by inspecting the IsPostback property of the Page object.
All asp.net buttons are "submit" buttons. Typically, you'll want to have a runat="server" attribute on your button so you can handle events for that specific button in your codebehind. While I can only think of a few select reasons for not, the primary one typically cited is that the runat="server" causes the control ID to be changed so that it is unpredictable in client scripts and CSS. If this is your reason, you can set the clientidmode to static on that control.

DELETE method not working

I have written a WebApi controller that contains the following method for deleting a client...
[HttpDelete]
public void DeleteClient(int id) {
// do stuff here
}
...and am trying to test it by using the following HTML on a web page...
<form method="DELETE" action="/api/ClientsXml/">
<table style="padding: 5px">
<tr>
<td>ID</td>
<td><input type="text" size="20" name="id" id="id" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Send" /></td>
</tr>
</table>
</form>
However, the DeleteClient method is never called. It passes the request through to the GetClient method instead.
Anyone any idea why? I've tried all sorts of variations, but I just can't get the delete method called.
#DimitryS's answer is correct, but I thought I'd build on it a little.
HTML forms only allow GET and POST operations. This is current in the HTML 5 spec as well as the HTML < 4 spec.
Other HTTP methods are allowed when using XMLHttpRequest which is what underlies jQuery's ajax functionality. So a good option could be to use jQuery for your PUTs, DELETEs, and it should work in all major browsers (some discussion of that in this pretty definitive SO question: Are the PUT, DELETE, HEAD, etc methods available in most web browsers?).
Lastly, I'll say that if you are just using the form to test your API, then why not try a browser extension instead:
e.g.
POSTMan for chrome
RESTClient for firefox
There are many more, but most allow you to save a test suite, set different headers, and so forth.
Browsers usually can only perform GET or POST for the form elements (unless you are submitting it using AJAX).
You should change the form method to POST and add the following HTML element:
<input name="X-HTTP-Method-Override" type="hidden" value="DELETE" />
That is the way MVC allows to override HTTP methods for synchronous POSTs.
Edit: this post explains how to make the Web API support the same convention:
https://stackoverflow.com/a/13135848/395359

How to get html input placeholder value from database in C#?

I have a HTML input text and place holder. I want to get a place holder value from a database but I want to do it programatically:
<td><input runat="server" placeholder="Title" type="text" /></td>
Any help would be appreciated.
First, you need to give the input a name so that you can reference it in code behind. Then, once you go grab the value that you want from the database you will do something like this:
inputName.Placeholder = DataRow[0]("TextFromDBColumnName").ToString();
Obviously you want to put all safeguards in place to make sure that the DataTable or DataReader you are using has data and that the value that came back from the database is not NULL, which I would safeguard against in the query or stored procedure.
As ammills01 said you've got to give the input an ID attribute so you can call it from code-behind:
<td><input ID="YourID" runat="server" placeholder="Title" type="text" /></td>
And then call it:
YourID.Placeholder = DataRow[0]("TextFromDBColumnName").ToString();

file upload in asp.net mvc 4 razor

I am using ASP .Net MVC 4.0 and VS10. I am a newbie in web application.
I have designed a page with html razor view. Here is some code of Index.cshtml:
#{
ViewBag.Title = "BAP Automation";
}
#section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
<h2>#ViewBag.Message</h2>
</hgroup>
<form action="Index">
<table> **//EDITED BELLOW**
<tr><form action="" method="post">
<td>Upload Excel File: </td>
<td><input type="text" name="NAMEtxtFileName"/></td>
<td><input type="button" value="Upload" id="IDbtnUpload" name="NAMEbtnUpload"/></td>
</form>
</tr>
<tr>
<td>Company Name: </td>
<td><input type="text" /></td>
<td></td>
</tr>
<tr>
<td></td>
<td align="right"><input type="submit" value="Process" /></td>
<td></td>
</tr>
</table>
</form>
</div>
</section>
}
I am trying to upload an excel file in NAMEbtnUpload's click event. clicking on this button we will be in this page, just a file upload dialog will open and selecting the file, the file location will be shown in the NAMEtxtFileName textbox.
EDIT 1:
I have written some code from the suggested code:
[HttpPost]
public ActionResult Index(HttpPostedFileBase NAMEbtnUpload)
{
if (NAMEbtnUpload.ContentLength > 0)
{
var fileName = Path.GetFileName(NAMEbtnUpload.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/Given Excel's"), fileName);
NAMEbtnUpload.SaveAs(path);
}
return RedirectToAction("Index");
}
but this shows following error:
Server Error in '/' Application.
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: /
Try adding the "EncType" attribute to your form.
#using (Html.BeginForm("ACTION", "CONTROLLER", FormMethod.Post, new { EncType="multipart/form-data"})){
//FORM MARKUP HERE
}
Phil Haack shows you how to handle file uploads with his blog post Uploading a File (Or Files) With ASP.NET MVC.
There is quite a bit of stuff you are missing so reading that post will get you further than any answer here.
** UPDATE FOR EDIT 1 **
A couple issues
<form action="index" > - this should be <form action="/ControllerName/Index">
You have multiple form tags that are nested. You can have multiple form tags but they can't be nested. In your case your only need one. Most of the time you only need 1.
<input type="button" value="Upload" id="IDbtnUpload" name="NAMEbtnUpload"/> should be
It is more conventional to use #using(Html.BeginForm()) as opposed to manually writing form tags. See below.
#using(Html.BeginForm("Index"))
{
<table>
<tr>
<td>Upload Excel File: </td>
<td><input type="text" name="NAMEtxtFileName"/></td>
<td><input type="file" id="IDbtnUpload" name="NAMEbtnUpload"/></td>
</tr>
<tr>
<td>Company Name: </td>
<td><input type="text" /></td>
<td></td>
</tr>
<tr>
<td></td>
<td align="right"><input type="submit" value="Process" /></td>
<td></td>
</tr>
</table>
}
clicking on [the upload] button we will be in this page, just a file upload dialog will open and selecting the file, the file location will be shown in the NAMEtxtFileName textbox.
That is not possible because a file upload element is not accessible programatically, anymore. "Back in the days" it was, and malicious sites silently uploaded sensitive information by setting the file upload control's value to well known password file locations and so on.
You'll just have to put an <input type="file" /> on your form and handle the upload serverside, as suggested in the link on #Bretts answer.
Set the name of file control in controller class.
for example in above code
public ActionResult Index(HttpPostedFileBase NAMEbtnUpload)
change NAMEbtnUpload to NAMEtxtFileName
this resolve your problem.

Categories

Resources