add custom data to POST - asp.net

I have a webpage that has 3 file inputs. There are specific fields on the form that needs to be sent when user uploads the file. I am not able to figure out how do i add custom data to my POST and how do i retrieve it back on the server. This is how my code looks like:
ASPX Page with 3 file inputs and other text boxes/dropdowns:
<form action="FilesUploader.ashx" method="post">
<div id="dvNewAttachment1">
<span>Attachment Type</span>
<select id="ddlAttachmentType1">
<option>T1</option>
<option>T2</option>
<option>T3</option>
</select>
<span>Description</span>
<input id="txtDesc1" />
<select id="ddlApproval1">
<option>Yes</option>
<option>No</option>
</select>
<input id="fileUploader1" type="file" runat="server" />
</div>
<br />
---------------
<div id="dvNewAttachment2">
<span>Attachment Type</span>
<select id="ddlAttachmentType2">
<option>T1</option>
<option>T2</option>
<option>T3</option>
</select>
<span>Description</span>
<input id="txtDesc2" />
<select id="ddlApproval2">
<option>Yes</option>
<option>No</option>
</select>
<input id="fileUploader2" type="file" runat="server" />
</div>
<br />
-------------------------------
<div id="dvNewAttachment3">
<span>Attachment Type</span>
<select id="ddlAttachmentType3">
<option>T1</option>
<option>T2</option>
<option>T3</option>
</select>
<span>Description</span>
<input id="txtDesc3" />
<select id="ddlApproval3">
<option>Yes</option>
<option>No</option>
</select>
<input id="fileUploader3" type="file" runat="server" />
</div>
<input type="submit" />
</form>
This is how my handler looks like:
public void ProcessRequest(HttpContext context)
{
HttpPostedFile myFile = context.Request.Files[0];
int nFileLen = myFile.ContentLength;
byte[] buffer = new byte[nFileLen];
using (BinaryReader br = new BinaryReader(myFile.InputStream))
{
br.Read(buffer, 0, buffer.Length);
}
}
As you can see i have 3 uploads and each has Attachment Type and description associated with it which i need to retrieve for each input file in my handler.
Right now i am just processing file from the first input but later i am going to loop thru the inputs and process them.

If your handler do not receive files that you place in file uploaders then your form needs to have additional attribute like this:
<form action="FilesUploader.ashx" method="post" enctype="multipart/form-data">
In order to get values from dropdowns on server you need to provide a name attribute to them:
<select id="ddlApproval1" name="ddlApproval1">
<option>Yes</option>
<option>No</option>
</select>

Related

pass value attribute from view to controller asp.net mvc

here was my code from view
#{ var companies = (IEnumerable<Company>)ViewData["companylist"]; }
#foreach (var item in companies)
{
//post the form to upload actions, index2 for testing
<form id="submitfinal" method="post" asp-action="Upload" asp-controller="report" enctype="multipart/form-data">
<input type="hidden" name="companyid" value="#item.Id" />
#item.Name (#item.Status)
<input type="file" name="files" />
<input name="submit" type="submit" value="upload final report" />
</form>
}
Question here was how can i take the data from input tag attribute to controller?
let say the #item.Id is 1234, how i get that in controller?
you can use
#Html.HiddenFor(m => m.yourPropertyname)
or using jquery ajax you can send the value to controller.
Maybe it's too late, but I would use asp-route-Id like:
<form id="submitfinal" method="post" asp-route-Id="#item.Id" asp-action="Upload" asp-controller="report" enctype="multipart/form-data">

spring+ thymeleaf unable to update

Hi I am working with spring MVC and thymeleaf and I am not able to update data from my controller as I have following code.The main problem I am facing is that my put method is not getting called.
#GetMapping("/{id}/edit")
public String editUser(#PathVariable("id") int id, Model model) {
logger.info("++++++++++++[edit User]\n\n" + userService.findById(id));
model.addAttribute("user", userService.findById(id));
return "user/edit";
}
#PutMapping("/{id}/edit")
public String updateUser(#PathVariable("id") int id, #ModelAttribute("user") User user, Model model) {
logger.info("\n\n+++++++++++++++++inside Update");
User toUpdate = userService.findById(user.getId());
user.setUserName(user.getUserName() != null ? user.getUserName() : toUpdate.getUserName());
user.setName(user.getName() != null ? user.getName() : toUpdate.getName());
logger.info(user.toString());
userService.updateUser(user);
model.addAttribute("user", userService.findById(user.getId()));
return "redirect:/user/" + id;
}
and my html page
<form action="#" th:action="#{/user/__${user.id}__}" method="put"
th:object="${user}">
<div class="form-group">
<label for="txtUserName">User-name</label> <input
class="form-control" id="txtUserName" placeholder="User Name"
th:feild="${user.userName}" />
</div>
<div class="form-group">
<label for="txtName">First Name</label> <input
class="form-control" id="txtName" placeholder="Full Name"
th:feild="${user.name}" />
</div>
<div class="form-group">
<label for="calDob">Date of Birth</label> <input
class="form-control" id="calDob" placeholder="dd/MM/yyyy" />
</div>
<button type="submit" th:method="put" class="btn btn-success">Update</button>
<a href="#" th:href="#{/user/__${user.id}__}"
class="btn btn-primary">Cancel</a> <a th:method="delete"
href="javascript:deleteUser('${user.id}');" class="btn btn-danger">Delete</a>
</form>
any help will be usefull thanks
PUT is not a valid argument for method attibute of the form tag. See HTML specification.
Valid methods are GET and POST. And as it's not a REST API, you can use POST method to update.
So just update your mapping from:
#PutMapping("/{id}/edit")
to
#PostMapping("/{id}/edit")
And form tag to:
<form action="#" th:action="#{/user/__${user.id}__}/edit" method="post" th:object="${user}">

Spring Boot with Thymeleaf post list

I want to post a list of strings to my controller.
But it always only take the first selected value.
my thymeleaf html form:
<form action="/add" method="post">
<div class="form-group">
<label for="roleId">ID</label> <input type="text" class="form-control" id="roleId" name="id" required="required" />
</div>
<div class="form-group">
<label for="rolePrivileges">Privileges</label>
<select class="form-control" id="rolePrivileges" name="privileges" multiple="multiple" size="10" required="required">
<option th:each="type : ${privilegesList}" th:value="${type}" th:text="${type}">Privilege</option>
</select>
</div>
<button type="submit" class="btn btn-default">Create</button>
</form>
my controller:
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addSomething(Model model, #ModelAttribute("id") String id,
#ModelAttribute("privileges") List<String> privileges) {
// add something with a service
return "redirect:/roles";
}
I think you have to Annotate the privilges with
#RequestParam("privileges")
It is not a ModelAttribute but you receive it from the request
Edit: two SO threads to better understand the difference between #RequestParam and #ModelAttribute.

Adding a database populated dropdown Razor

just started learning to make dynamic pages with WebMatrix and have run into a road block. (Long history of static html and some php using notepad++, but this is new to me.)
In short: I'm trying to give people the option of creating a new team entry in the database OR joining an existing team from a html helper dropdown list populated from the database. I've been trying various ways of doing this for the better part of two days and can't seem to figure it out after extensive searchers here and on ASP.net. I'm also hoping to figure out how to allow either the creation of a new team or joining an existing team already in the DB on the same page without getting commas inserted into the database.
I've removed all my attempts at a dropdown and am sharing what currently works without the html.dropdown:
#{
Validation.RequireField("FName", "Your first name is required");
Validation.RequireField("LName", "Your last name is required");
Validation.RequireField("Team", "A team is required to play");
Validation.RequireField("Pledge", "You must donate to play.");
var db = Database.Open("BBBT");
var FName = Request.Form["FName"];
var LName = Request.Form["LName"];
var Team = Request.Form["Team"];
var Pledge = Request.Form["Pledge"];
if (IsPost && Validation.IsValid()) {
if(ModelState.IsValid) {
var insertQuery = "INSERT INTO Players (FName, LName, Team, Pledge) " +
"VALUES (#0, #1, #2, #3)";
db.Execute(insertQuery, FName, LName, Team, Pledge);
Response.Redirect("~/ListTeams");
}
}
}
....Snip....
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<h1>Register</h1>
#Html.ValidationSummary("Errors with your submission:")
<form method="post" action="">
<fieldset>
<legend>Join the fun!</legend>
<div>
<label>First Name:</label>
<input name="FName" type="text" size="50" value="#FName" />
</div>
<div>
<label>Last Name:</label>
<input name="LName" type="text" size="50" value="#LName" />
</div>
<div>
<label>Create a Team</label>
<input name="Team" type="text" size="50" value="#Team" />
</div>
<div>
<label>Or Joing an Existing Team</label>
<!-- This is where I would like to put the Dropdown list-->
#Html.DropDownList
</div>
<div>
<label>Pledge:</label>
<input name="Pledge" type="text" size="50" value="#Pledge" />
</div>
<div>
<label> </label>
<input type="submit" value="Insert" class="submit" />
</div>
</fieldset>
</form>
</body>
</html>
Any direction would be greatly appreciated!
Thank you.
Your will be getting the result in two steps. First Generate the List, then display it.
In the code block at the top of the page add this code
List<string> Teams = new List<string>();
foreach(var row in db.Query("SELECT DISTINCT Team FROM Players"))
{
Teams.Add(row.Team);
}
and in the place you want the dropdown populate the list
<select name="Team">
#foreach(string Teamname in Teams)
{
<option value="#Teamname ">#Teamname </option>
}
</select>
EDIT:
<select name="Team" id="TeamDropdown" onchange="toggleteamcreation()">
#foreach(string Teamname in Teams)
{
<option value="#Teamname ">#Teamname </option>
}
<option value"New">Create New Team</option>
</select>
<script>
function toggleteamcreation(){
if(document.getElementById('TeamDropdown').value=="New"){
document.getElementById('Create_New_Team').style.display="block";
}
else{
document.getElementById('Create_New_Team').style.display="none";
}
}
</script>
<div id="Create_New_Team" style="display:none">
<label>Create a Team</label>
<input name="Team" type="text" size="50" value="#Team" />
</div>

Input type="file" server side access

I have the following client side code:
<form action="PhotoStore.aspx" id="form1" method="post" enctype="multipart/form-data">
<div>
<input type="file" id="file"/>
<input type="submit" />
</div>
</form>
With this client side code, how will I access the uploaded file in Photostore.aspx? Request.Files is having a count = 0 :( .? Whats going wrong?
You need to put a name on the input field, or it won't be included in the form data:
<input type="file" name="file"/>
What about
Page.Request.Form["file"]

Resources