Is it possible to include a file with a form POST - asp.net-mvc

I got a regular POST in my mvc app:
#using (Html.BeginForm("Update", "AController", FormMethod.Post))
{
<div style="margin-bottom:20px"></div>
#Html.AntiForgeryToken()
<div class="form-input">
<input class="form-control" type="text" name="#(nameof(Model.Name))" value="#(Model.Name)" />
</div>
<br />
<div class="form-input">
<input class="form-control" type="text" name="#(nameof(Model.Name2))" value="#(Model.Name2)" />
</div>
<br />
<div>
<input type="file" name="Image" id="Image" name="#(nameof(Model.Image))" value="#(Model.Image)" />
</div>
<button type="submit" class="btn btn-primary btn-sm">TEXT HERE</button>
}
Now when doing the submit the two regular text fields gets binded the model but the file does not.
After some reading it seems like the upload part should be in a separate form, is that correct?
I really want to avoid having two different POST as it does not fit the design of the page.

You should be able to get the posted file from the Request directly in the controller with following code
if(Request.Files.Count > 0)
{
var file = Request.Files[0];
...
}
But you need to add the multipart/form-data to your form
#using (Html.BeginForm("Update", "AController", FormMethod.Post, new { enctype="multipart/form-data" }))
Check What does enctype='multipart/form-data' mean? for reference on the multipart/form-data

Related

file uploding action not get invoke

I'm working on ASP.Net MVC project using Visual Studio 2017 . When i click File upload button it not direct to controller method it directs to a blank page .This page worked as expected Few hours ago nothing changed ,but now im getting this issue Browser console gives me this error .
The character encoding of the plain text document was not declared.
The document will render with garbled text in some browser
configurations if the document contains characters from outside the
US-ASCII range. The character encoding of the file needs to be
declared in the transfer protocol or file needs to use a byte order
mark as an encoding signature
.
View code
#using Microsoft.AspNetCore.Mvc.Localization
#inject IViewLocalizer Localizer
<div class="box">
<div class="box-header">
<h3 class="box-title">#Localizer["ImportWorkFile"]</h3>
<h1>#ViewBag.message</h1>
<form action="#Url.Action("ImportWorkers")" method="post" enctype="multipart/form-data">
<input type="hidden" name="OrganizationId" value="#Model"/>
<input type="hidden" name="send" value="true" />
<div class="form-horizontal">
<div>#Localizer["Only"] <strong>.csv</strong> #Localizer["FileSuported"]</div>
<div class="form-group">
<label for="importFile" class="col-md-2 control-label"></label>
<div class="col-md-12">
<input id="importFile" name="csvFile" type="file" class="form-control" required />
</div>
</div>
<input type="submit" name="name" value="#Localizer["Send"]" />
</div>
</form>
</div>
</div>
Controller Method
[HttpPost]
public ActionResult ImportWorkers(bool send, long OrganizationId)
{
}

Get method : form input not in url

I am doing my first ASP.NET mvc project, on the home page, Index.cshtml, I have a small form:
<form action="ChoixFormulaire" method="get">
<fieldset>
<label>NAS</label>
<input id="nas" type="text" placeholder="###"/>
<br />
<label>Date of birth</label>
<input id="date" type="text" placeholder="AAAA-MM-JJ"/>
<br />
<label>Employee number</label>
<input id="numEmployee" type="text" placeholder="######"/>
<br />
</fieldset>
<input type="submit" value="Soumettre" onclick="return VerifierFormulaire()" />
</form>
When the button is clicked, there is some verification made in the 'VerifierFormulaire()' method, which is defined in the same Index.cshtml file. Then the ChoixFormulaire.cshtml is displayed (called from the ChoixFormulaire() method in my HomeController, which returns View()).
I was expecting the form inputs to be in the URL as parameters. For example, If I enter '123' for NAS, '1989-01-01' for date of birth and '123456' for employee number, I am redirected to http://localhost:15778/Home/ChoixFormulaire? but I would expect to be redirected to http://localhost:15778/Home/ChoixFormulaire?nas=123&dateBirth=1989-01-01&numEmployee=123456
Try adding the name attribute:
<input id="nas" name="nas" />

POST and GET in the same form created by BeginForm method

How to create a form that has a search function (pull data from the database) AND a submit function (add data to the database) at the same time using the BeginForm() method? I am reviewing the overloads on MSDN and I don't seem to find one.
Code:
#using (Html.BeginForm()){
<table>
#*Bunch of textboxes and dropdown lists*#
</table>
<div id=" buttonHolder">
<input id="Search" type="button" value="Search" />
<input id="Reset1" type="reset" value="Reset" />
<input id="Submit1" type="submit" value="Add" />
</div>
}
You can use two approaches here:
handle onsubmit and fetch/save data with AJAX (you can do it even with Html.BeginForm but it's easier to go just with regular <form ...)
#using (Html.BeginForm("DoIt", "DoItAction", FormMethod.Post, new { onsubmit = "submitWithAjax(event); return false;" }))
create two separate forms with a different action/controller pair

How to make SignUp/Login action in one form

I working on my first ASP.net MVC project and and i got some problems using multiple buttons in one form.
When my user type username&password and then hit login means it will go to welcome page
if user try to Sign Up means it will go to another form field to get Personal information.
and finally all given information need to store in database and redirect user to welcome page .
#using (Html.BeginForm("about", "home", FormMethod.Post, new { #id = "msform" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<!-- progressbar -->
<ul id="progressbar">
<li class="active"></li>
<li></li>
<li></li>
</ul>
<!-- fieldsets -->
<fieldset>
<h2 class="fs-title">Create your account</h2>
<h3 class="fs-subtitle">Take 60 Seconds With Us</h3>
<input type="text" name="UsersName" placeholder="Username" />
<input type="password" name="Passsword" placeholder="Password" />
<input type="button" name="next" class="next action-button" value="Sign Up" />
<input type="button" name="next" class="nexts action-login" value="Log In" />
<input type="submit" value="+" />
</fieldset>
<fieldset>
<h2 class="fs-title">Personal Information</h2>
<h3 class="fs-subtitle">We will never share</h3>
<input type="text" name="phone" placeholder="Email" />
<input type="text" name="phone" placeholder="Phone Number" />
<input type="text" name="date" placeholder="Date of Birth" />
<input type="text" name="gender" placeholder="Gender" />
<input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
<fieldset>
<h2 class="fs-title">Make SomeOne Alive</h2>
<h3 class="fs-subtitle">A donor today! A hero tommorow!</h3>
<input type="text" name="fname" placeholder="Blood Group" />
<input type="text" name="lname" placeholder="Are You ?" />
<input type="text" name="phone" placeholder="State" />
<input type="text" name="phone" placeholder="City" />
<input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="submit" name="submit" class="action-button" value="Submit" />
</fieldset>
}
But now that I have a login button placed on my view form, I'm totally lost. I don't know how to make when user click login button means it will redirect ,if signUp means it will redirect to another form. How to implement the form
Give your button names, and then test for their existence in the posted data server-side. Only the one that is clicked will be there:
<button type="submit" name="_SignUp">Sign Up</button>
<button type="submit" name="_LogIn">Log In</button>
Then, in your action:
if (Request.Unvalidated["_SignUp"] != null)
{
// do sign up
}
if (Request.Unvalidated["_LogIn"] != null)
{
// do log in
}
Or, you can alternatively just divine the user's intention, by attempting to retrieve the user object to sign them in, and if you get no match, then doing the signup instead. However, that pretty much makes the buttons unimportant and could result in the user clicking "Sign Up" and actually being logged in, instead, or vice versa. It doesn't really matter, but it's better to manage user's expectations. If they think they don't have an account, but actually do, they might want to know that.

Multiple Submit buttons in Form neither appearing in FormCollection of ASP.Net MVC Method

I'm at my wits end here...I have the following razor markup for my form:
<input class="k-button" type="submit" value="Post" name="SubmitButton" />
<input class="k-button" type="submit" value="Save" name="SubmitButton" />
The problem I'm experiencing is that the FormCollection parameter of the controller action method does not include SubmitButton in its Key/Value pairs.
I've come across this post here that seems to have had the same problem. The solution seemed to be to use a ActionMethodSelectorAttribute AND to remove the use of [Remote] validation. But I really need my [Remote] validator though, so it is not an option for me to remove that. Is there no other solution, or is this some bug I just have to deal with?
I'm thinking along the lines of having to replace my use of two buttons with a single Save button, and then add a "Post" checkbox. Then in the controller action I check for the presence of the Post KeyValue pair. But this is less than idea. I prefer the use of two buttons.
EDIT: more view markup following Igor's request:
#using (Html.BeginForm())
{
#Html.ValidationSummary(false)
<fieldset>
<legend>Edit details for Client Warehouse Request </legend>
#Html.HiddenFor(model => model.ModelObject.CustomerCode)
#Html.HiddenFor(model => model.ModelObject.ReqNr)
<div style="table-layout: initial;">
<div class="columnDivider">
<div class="editor-label">
#Html.LabelFor(model => model.ModelObject.ReqNr)
</div>
<div class="editor-field">
#Html.DisplayFor(model => model.ModelObject.ReqNr)
</div>
<div class="clear">
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ModelObject.CreationDate)
</div>
... many other fields following the above structure...
<input class="k-button" type="submit" value="Post" name="SubmitButton" />
<input class="k-button" type="submit" value="Save" name="SubmitButton" />
</div>
<div class="columnDivider">
...some more fields
</div>
<div>
Here I have a Kendo UI datagrid that gets submitted with the form
</div>
</fieldset>
}
Try:
<input type="hidden" name="SubmitButtonValue" id="SubmitButtonValue" />
<input class="k-button" type="submit" value="Post" name="SubmitButton" />
<input class="k-button" type="submit" value="Save" name="SubmitButton" />
<script type="text/javascript">
$(document).ready(function(){
$(".k-button").click(function(){
$("#SubmitButtonValue").val($(this).val());
});
});
</script>
and check for "SubmitButtonValue" key in FormCollection.

Resources