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).
Related
I have a bit of a dilemma. I have a table of 3 columns. Column 1 is a button to make that row active. The 2nd column is the name of the person. And the 3rd column is a button to view the person's details.
Using Selenium C#, I can search for a specific person in the table and click the button to View, using the code below:
currentDriver.FindElement(By.XPath("(.//*[normalize-space(text()) and normalize-space(.)='Name of person'])")).Click();
How do I select the button before the name of the person?
EDIT: Added HTML -
<table class="table table-hover>
<thead>...</thead>
<tbody id="listCompany">
<tr>
<td>
<span id="a5" class="badge btnActivateCompany clsActiveCompany15" ><i class="fas fa-times"></i></span>
</td>
<td>Test Director</td>
<td>
<button.>...</button>
</td>
</tr>
</tbody>
The class btnActivateCompany is used several times depending on how many rows exist. And the id changes depending on the rows as well. So I have to search to find the correct record and then select the span before it.
I tried the following to select the object:
currentDriver.FindElement(By.XPath("(.//*[normalize-space(text()) and normalize-space(.)='Test Director'])[1]/preceding::span[1]")).Click();
I get the feeling you've modified the HTML as you've posted. I guess you stripped out some data and typed other content in. You say you want the button before the person, but in your code the button is after the person?
Either way, both are achievable. I made a few quick additions to help visibility. If i'm wrong please correct me as it influences xpaths.
Quick change log: I ran your html through a beautifier, added text to all the columns for visibility, added "border=1" to the table, remove the . from button, added the </table> and duplicated the row so i can check unique objects are found.
This is the result: (useful if anyone else wants to chip in an identifier)
<html>
<body>
<table class="table table-hover" border=1>
<thead>...</thead>
<tbody id="listCompany">
<tr>
<td>
<span id="a5" class="badge btnActivateCompany clsActiveCompany15" >
<i class="fas fa-times"> Column 1</i>
</span>
</td>
<td>Test Director</td>
<td>
<button> Button in col 3
</button>
</td>
</tr>
<tr>
<td>
<span id="a5" class="badge btnActivateCompany clsActiveCompany15" >
<i class="fas fa-times"> Column 1</i>
</span>
</td>
<td>Second Row!</td>
<td>
<button> Button in col 3
</button>
</td>
</tr>
</tbody>
</table>
</body>
</html>
That renders like this:
Based on fact you say you can get the text in the middle column...
If you want the button in column 3, you can try xpath:
//td[text()='Test Director']/parent::*/td/button
If you want the span in column 1, you can try:
//td[text()='Test Director']/parent::*/td/span[contains(#class,'btnActivateCompany')]
In both of these instances this selects a unique hit in the source.
However, please note, this is dependent on the html provided. If there are other elements/attributes in the table the xpath might need more work. I'm happy to help more but you'll need to share more content.
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.
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.
I am new at MVC and have a view that has a search text box + button a navigation tab and table.
I would like the table to be populated only when the search criteria is entered and the button clicked.
The problem I am having now is that the table section of the view is rendered and returns a null object reference error when the page is loaded.
Other than using jquery/java functions how can I get the table to only populate when the the search criteria is entered and the button clicked?
Do I need to create 2 separate views(one with the table and one without)?
Here are parts of my view:
<div class="searchBox">
<label>Please search here
<input type="text" name="searchTerm" id="searchTerm" value="<%= !string.IsNullOrEmpty((string) ViewData["SearchTerm"]) ? Html.Encode(ViewData["SearchTerm"]) : "" %>" />
<input type="button" value="Add" />
</label>
</div>
<ul class="navigation">
<li><a class="selected" href="#name" >Person1</a></li>
<li>Person2</li>
<li>Person3</li>
<li>Person4</li>
</ul>
<div class="tabSection">
<div class="basic">
<table id="person" class="gridview">
<thead>
<tr>
<th>name</th>
<th>dob</th>
<th>address</th>
<th></th>
</tr>
<tr>
<td><%= Model.name %></td>
<td><%= Model.dob%></td>
<td><%= Model.address%></td>
<td></td>
</tr>
</thead>
</table>
</div>
</div>
You should just wrap your table in this:
#if (Model != null)
{
// table code
}
Also, you might want to consider putting your table logic into a partial view, and have the if statement in the partial view. That way, in your main view you could just have Html.RenderPartial("PARTAILVIEWNAME"); Doing it this way would allow you to have the same table in as many views as you want without having to remember to wrap the table in an if statement every time.
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