I have a form in my asp.net web app, which sends files uploaded by the user
<form method="post" asp-action="#((Model != null) ? "Update" : "Upload")" asp-controller="Materials" enctype="multipart/form-data">
<input id="cat" type="hidden" name="cat" />
<input id="subcat" type="hidden" name="subcat" />
<input type="file" name="file" max="1" title="#((Model != null) ? "Обновить" : "Загрузить")"/><br />
<input type="file" name="images" multiple title="Загрузить картинки"/><br />
<input id="name" type="text" name="name" maxlength="30" /><br />
<textarea id="desc" name="description" maxlength="199" ></textarea><br/>
<input type="submit" value="Сохранить"/>
</form>
There is one input for a file, and one input for image files, but as soon as I input any files the app just.... shuts down
Here is the method from the controller:
[HttpPost]
public IActionResult Upload(IFormFile file, IFormFileCollection images, string name, string description, string cat, string subcat)
{
FileUploadManager f = new FileUploadManager(environment.WebRootPath + '/');
f.Upload(file,images, name, description, cat + "-" + subcat);
return Redirect(Url.Action("Index", "Material"));
}
the browser does not shut down, the app itself in the VS does, and without any exceptions, it just stops debugger as soon as files contact with HTML
also, I am using Yandex browser
Related
I am trying to implement Sign Up api of Constant Contact. They gave me this HTML code. Runs properly if i save it as a HTML page.
What i want to do is convert this form to C# code that will execute onClick of a button. The HTML portion is looking fine but today is my first day with ASP.net and i have no idea what code to put in the code-behind .cs file. Searched a lot and am super confused.
This method is clicked when the submit button is clicked:
protected void buttonId_Click(object sender, EventArgs e)
{
}
Here is my ui side code:
<asp:TextBox ID="TextBox3" runat="server" class="name" value="First Name" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'First Name';}"></asp:TextBox>
<asp:TextBox ID="TextBox4" runat="server" class="name" value="Last Name" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Last Name';}"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" class="name" value="Join our mailing list" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Join our mailing list';}"></asp:TextBox><br>
<asp:Button id="buttonId" OnClick="buttonId_Click" class="btn btn-info sub1" runat="server" Text="SUBSCRIBE">
</asp:Button>
Here is the HTML code that i got from constant contact:
<form data-id="embedded_signup:form" class="ctct-custom-form Form" name="embedded_signup" method="POST" action="https://visitor2.constantcontact.com/api/signup">
<p>Sign up to get interesting news and updates delivered to your inbox.</p>
<!-- The following code must be included to ensure your sign-up form works properly. -->
<input data-id="ca:input" type="hidden" name="ca" value="my-secrect-key">
<input data-id="list:input" type="hidden" name="list" value="3">
<input data-id="source:input" type="hidden" name="source" value="EFD">
<input data-id="required:input" type="hidden" name="required" value="list,email">
<input data-id="url:input" type="hidden" name="url" value="">
<p data-id="Email Address:p" ><input data-id="Email Address:input" type="text" name="email" value="" maxlength="80"></p>
<p data-id="First Name:p" ><input data-id="First Name:input" type="text" name="first_name" value="" maxlength="50"></p>
<p data-id="Last Name:p" ><input data-id="Last Name:input" type="text" name="last_name" value="" maxlength="50"></p>
<button type="submit" class="Button ctct-button Button--block Button-secondary" data-enabled="enabled">Sign Up</button>
</form>
Here's an example of some code you could put in your button OnClick event. This POST's data to another URL.
Hopefully you can figure out what's going on in this code. Basically it is building a string (data) with all of the data from the HTML form and submitting this to the other website using HTTP POST.
Most likely you would also need to check the response back from the other website.
string remoteUrl = "https://visitor2.constantcontact.com/api/signup";
ASCIIEncoding encoding = new ASCIIEncoding();
string data = "ca=my-secrect-key&list=3&source=EFD&required=list,email&url=&email=" + Server.UrlEncode(TextBox1.Text) + "&first_name=" + Server.UrlEncode(TextBox2.Text) + "&last_name=" + Server.UrlEncode(TextBox3.Text);
byte[] bytes = encoding.GetBytes(data);
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(remoteUrl);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.ContentLength = bytes.Length;
using (Stream stream = httpRequest.GetRequestStream())
{
stream.Write(bytes, 0, bytes.Length);
stream.Close();
}
I want to create a register form using MVC which include a profile photo. I don't want to add record for people before completing the form (including profile photo upload). Also I want my UploadImage view and controller to be re-usable for many forms (not just this form). I pass three variables to my upload form through ActionLink: RedirectAction (RA), RedirectController (RC), and dataname and the procedure goes like this:
I store RA, RC, dataname in ViewBag, then put them in hidden <input> tags to be submitted when POSTing the file
// GET: UploadImage/Upload
public ActionResult Upload(string RA, string RC, string dataname)
{
ViewBag.RedirectAction = RA;
ViewBag.RedirectController = RC;
ViewBag.DataName = dataname;
return View();
}
Put these lines in my Upload.cshtml (View):
#using (Html.BeginForm("Upload", "UploadImage", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="hidden" name="RA" value="#ViewBag.RedirectAction" />
<input type="hidden" name="RC" value="#ViewBag.RedirectController" />
<input type="hidden" name="dataname" value="#ViewBag.DataName" />
<input type="submit" name="Submit" id="Submit" value="Upload" />
}
Store the filename in TempData with dataname as the Key and redirect to /RC/RA:
// POST: UploadImage/Upload/
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, string RA , string RC , string dataname)
{
var filepath = "C:/myfilename.jpg";
TempData.Add(dataname, filepath);
return RedirectToAction(RA,RC);
}
And get my filepath by utilizing TempData in my register form:
#if (TempData.Keys.Contains("MyData")) {
<div class="form-group">
<p>#TempData["MyData"].ToString()</p>
</div>}
The code works just fine, but the essential caveat is that I don't want other completed fields to get lost when redirected to the register form. How can I solve this problem ?
One option is to stick the data in the session. Another option would be to use a separate database table to hold in-progress registration data.
I try to user an input type file to upload a file but my code don't work.
the variable "filePosted" stay to null value.
My code :
HTML :
<form method="post" name="gestionmembre" runat="server" enctype="multipart/form-data">
#using (Html.BeginForm()){
<label class="lmembre" for="nom">Nom:</label>#Html.TextBox("nom")<br />
<label class="lmembre" for="prenom">Prénom:</label>#Html.TextBox("prenom", Request["Prenom"])<br />
<label class="lmembre" for="mail">Mail:</label>#Html.TextBox("mail", Request["mail"])<br />
<label class="lmembre" for="photo">Photo:</label><input id="phototelecharge" type="file" name="photo" value="Télécharger photo"/> <br />
<div class="errorform">#Html.ValidationSummary()</div>
<input id="ajoutmembre" type="submit" name="boutonmembre" value="Ajouter"/>
}
</form>
I don't know if I have to put this atributes in form tag (method runat enctype).
now, in the controler, in block to receive form values, I put :
else if (Request["boutonmembre"] == "Ajouter")
{
//Traitement de l'upload de l'image
HttpPostedFile filePosted;
filePosted = System.Web.HttpContext.Current.Request.Files["phototelecharge"];
if (filePosted != null && filePosted.ContentLength > 0)
{
string fileNameApplication = System.IO.Path.GetFileName(filePosted.FileName);
string fileExtensionApplication = System.IO.Path.GetExtension(fileNameApplication);
// generating a random guid for a new file at server for the uploaded file
string newFile = Guid.NewGuid().ToString() + fileExtensionApplication;
// getting a valid server path to save
string filePath = System.IO.Path.Combine(Server.MapPath("uploads"), newFile);
if (fileNameApplication != String.Empty)
{
filePosted.SaveAs(filePath);
}
}
}
The problem is in :
filePosted = System.Web.HttpContext.Current.Request.Files["phototelecharge"];
The variable fileposted is null.
In the webpage, I select a file fro a disk and the path of the file is realy indicate in the textbox.
Tks for help me.
David
Here is a simple example
Controller
namespace stackoverflow.Controllers
{
public class HomeController : Controller
{
public ActionResult PostFile(HttpPostedFileBase myFile)
{
System.Diagnostics.Debugger.Break();
return View();
}
}
}
View
#using (Html.BeginForm("PostFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div id="postdata">
<input type="file" name="myfile" id="myFile" />
<input type="submit" value="submit" />
</div>
}
I have a form which looks, simplified, like this:
<form id="image-form" enctype="multipart/form-data">
<input type="text" name="imageEntryName" />
<input type="file" name="imageEntry" />
<input type="text" name="imageEntryAltText" />
<input type="submit" value="SEND INN" class="btn-ok" />
</form>
This is posted to this action:
[HttpPost]
[Route("~/api/Exhibition/SubmitImageEntry")]
public async Task<HttpResponseMessage> SubmitImageEntry()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
var provider = new MultipartFormDataStreamProvider("C:/test");
var data = await Request.Content.ReadAsMultipartAsync(provider);
return new HttpResponseMessage(HttpStatusCode.OK);
}
And this works. I get the posted data. But is this possible without the MultipartFormDataStreamProvider saving files to C:/test? I possible, I can just keep the data in memory until the action is completed.
EDIT: With MultipartFormDataStreamProvider I get the .FormData["key"] option, which is what I want.
Use the MultipartMemoryStreamProvider.
I have a asp.net mvc application with razor engine.
In a view Home i have this snippet:
<section id="form_admin">
<form action="/Super/Manipuler" method="post">
<fieldset>
<legend>Formulaire d'ajout d'un administrateur</legend>
#Html.Label("Login")
#Html.Label("Mail")
#Html.Label("Password")
#Html.Label("Name")
<br />
<br />
#if(Model != null){
foreach (Upload.Models.AdminModels admin in Model)
{
if (i == 0){
<input type="radio" checked class="radio" name="radio" value="#admin.Login" >
}
else{
<input type="radio" class="radio" name="radio" value="#admin.Login" style="margin-left:0.3px;">
}
<label id="log">#admin.Login</label>
<label id="logm">#admin.Mail</label>
<label id="logp">#admin.Password</label>
<label id="logn">#admin.Name</label>
<br />
i++;
}
}
<br />
<input type="submit" value="Editer" name="submit_button"/>
<input type="submit" value="Supprimer" name="submit_button" />
Créer un nouveau compte
</fieldset>
</form>
</section>
In the controller : the action Manipuler is the below:
public ActionResult Manipuler()
{
string buttonName = Request.Form["submit_button"];
string _login = Request.Params["radio"];
Upload.Models.AdminModels admin = new AdminModels();
Upload.Models.CompteModels.Modifiying_login = _login;
if (buttonName == "Editer") { return RedirectToAction("Edit", "Admin"); }
else { admin.Delete_admin(_login); return RedirectToAction("Home", "Super"); }
}
It's works fine but i'd like to change the radiobox to checkbox.
My question is how to know all checked box in the collection of checkbox in the action Manipuler ?
Take a look at Phil Haack's article on model binding a checkbox list. Basically, you just need to set up the HTML in a specific way (name your checkboxes the same which will then convert the various POSTed values into a list).
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx