HttpPostedFileBase in ASP.NET MVC is null while using jQuery Dialog - asp.net-mvc

File upload paths in MVC is null with jquery dialog
I have created a MVC application having two file uploads in view and created a POST action for this, with IEnumerable parameter to catch the files. When i am submitting the form the files are coming fine in the HttpPostedFileBase collection, but if the file upload controls are in a dialog(jquery pop up) the IEnumerable object is null. Please help me.
The following are the codes i have done.
View
#using (Html.BeginForm("Details", "StudentRegistration", FormMethod.Post, new{ #class = "form ideal-form",enctype = "multipart/form-data"}))
{
<div id="divSignatureCapturePopUp" title="Capture Photo" style="display:none; float:left;">
<input id="fileUploadSignature" type="file" name ="fileUploadImages" style="width:200px"/>
</div>
}
<input type="button" id="buttonCaptureSignature" name="CaptureSignature" class="ideal-button" value="Capture Signature" />
<script type="text/javascript">
$(document).ready(function () {
$("#buttonCaptureSignature").click(function () {
$("#divSignatureCapturePopUp").dialog({
width: 560,
});
});
}
</script>
controller
[HttpPost]
public ActionResult Details(IEnumerable<HttpPostedFileBase> fileUploadImages)
{
}

Seems like jqueryui widget move file input field outside form. Check posted data in chrome dev console in 'Network' tab and make sure that file data is in request.
If this suggestion is right you can modify form this way:
<div id="divSignatureCapturePopUp" title="Capture Photo" style="display:none; float:left;">
#using (Html.BeginForm("Details", "StudentRegistration", FormMethod.Post, new{ #class = "form ideal-form",enctype = "multipart/form-data"}))
{
<input id="fileUploadSignature" type="file" name ="fileUploadImages" style="width:200px"/>
<input type="submit" value="rtwert" />
}
</div>
Оtherwise possible get files in other way:
[HttpPost]
public ActionResult Details()
{
var files = Request.Files;
}

Related

unable to get all uploaded file in mvc 5

I have two file upload control with different name and id.
But when i am uploading multiple file ,i am receiving only one file of each control.
Below is my code.
Main View
#using (Ajax.BeginForm("Questionnaire", "Tax", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "divQuestionnaire" }, new { id = "formquestionnaire", enctype = "multipart/form-data" }))
{
<div class="clearfix" id="divQuestionnaire">
#{ Html.RenderPartial("_Questionnaire");}
</div>
}
Partial view where file upload control is placed
<input id="PhotoUrl" type="file" class="upload" multiple="multiple" name="PhotoUrl" />
<input id="AddressUrl" type="file" class="upload" multiple="multiple" name="AddressUrl" />
<button type="submit">Save</button>
controller
public ActionResult Questionnaire(HttpPostedFileBase[] PhotoUrl, HttpPostedFileBase[] AddressUrl)
{
}
also tryied this not working
public ActionResult Questionnaire(IEnumerable<HttpPostedFileBase> PhotoUrl, IEnumerable<HttpPostedFileBase> AddressUrl)
{
}

Update and ASP.NET MVC model on button click

I'm new to ASP.NET MVC. I'm trying to update model on button click with no success: every time I push the button an HttpGet controller method is invoked.
Here is my markup
#model DataInterface.Model.Entry
<button onclick="location.href='#Url.Action("Survey")'">Finish survey</button>
Here is Controller code
[HttpGet]
public ActionResult Survey()
{
var entry = new Entry();
return View(entry);
}
[HttpPost]
public ActionResult Survey(Entry newEntry)
{
// save newEntry to database
}
When I click button HttpGet method is invoked. Why?
It is bad to be a rookie)
Thanks to all!
If you access a URL without explicitly specifying the HTTP method, ASP.NET MVC will assume a GET request. To change this, you can add a form and send it:
#using (Html.BeginForm("Survey", "Controller", FormMethod.Post))
{
<input type="submit" value="Finish survey" />
}
If you do this, your POST method will be invoked. The Entry parameter, however, will be empty, since you do not specify any values to send along with the request. The easiest way to do so is by specifying input fields, e.g. text inputs, dropdown, checkboxes etc.
#using (Html.BeginForm("Survey", "Controller", FormMethod.Post))
{
#Html.TextBoxFor(m => m.Title)
<input type="submit" value="Finish survey" />
}
If you have the object stored on the server somewhere and only want to finish it off by writing it into the database or changing its status, you could pass the Id of the object (or some temporary Id) along the post request and make the controller method work only with the Id:
#using (Html.BeginForm("Survey", "Controller", FormMethod.Post))
{
#Html.HiddenFor(m => m.Id)
<input type="submit" value="Finish survey" />
}
[HttpPost]
public ActionResult Survey(Entry newEntry)
{
// newEntry.Id will be set here
}
#using (Html.BeginForm("Survey", "<ControllerName>", FormMethod.Post))
{
<input type="submit" value="Finish survey" />
}
you must declare your form
#model DataInterface.Model.Entry
#using (Html.BeginForm("action", "Controlleur", FormMethod.Post, new {#class = "form", id = "RequestForm" }))
{
<input type="submit" value="Finish survey" />
}

Client form validation not working with modal dialog in MVC

I am changing a create form to become a modal dialog and jquery Unobtrusive validation stops working and don't know how to fix it.
Index.cshtml has a link to trigger a modal dialog.
Create
#section scripts{
<script type="text/javascript">
$('#createCustomer').on('click', function () {
$.get('/Customer/Create', function (data) {
$('#modalContainer').html(data);
$('#myModal').modal({});
});
});
Create.cshtml is a partial view.
#model Demo.Web.Models.CustomerVm
#using (Html.BeginForm("Create", "Customer", FormMethod.Post, new { #id="createForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Customer</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
On the controller there is an actionmethod which returns a partial view for create form.
public ActionResult Create()
{
return PartialView("Create");
}
view modal
public class CustomerVm
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
before i changed it to be a modal dialog .. everything was working but now i don't know how to fix it. How can i make validation work with dialog? Obviously, I don't want to rewrite validation rules on client script .. i want to get it working from view model .. thanks.
Because the form is not added to the page when the page loads, the unobtrusive validation will not pick it up. There are two ways to fix this.
Include the form on the page during the initial load. This will cause the form to be recognized and validation will occur. You can throw the partial view in a hidden div. Then your JavaScript will just show the modal dialog.
Manually register the form with the unobtrusive validation after adding it to the page. Something like $.validator.unobtrusive.parse("#id-of-the-form");
If you are loading the dialog dynamically just register the unobtrusive validation in the containing element's change event:
$('#modal-container').change(
function() {
$.validator.unobtrusive.parse("#your-form-id");
});
In partialview of create page -> modal-header, model-body, modal-footer and javascript code in the <script>your code </script> - don't put <script>your code</script> in #section Scripts{} and it will work.
Just add the following scripts in your Create form view:
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript">
</script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript">
</script>
Adding a new comment to share a more modern solution:
Use BundleConfig.cs in the App_Start folder of your MVC project.
namespace MySolution
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/Site.min.css",
"~/Content/bootstrap.min.css"));
bundles.Add(new ScriptBundle("~/Scripts/js").Include(
"~/Scripts/jquery-3.3.1.min.js",
"~/Scripts/jquery.validate.min.js",
"~/Scripts/jquery.validate.unobtrusive.min.js"));
}
}
}

how to upload file in Strong-Type view in ASP.NET MVC

I use:
#using (Html.BeginForm("UploadPackage", "Manager"))
to send webForm data to UploadPackage action.
Now I add an input tag whose type is file(< input type = "file" />) in that strong-type view. What I want to do is: How can I get all data from webForm (including file) in my Action and handle them?
Form in view:
#using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary();
<ol>
<li class="lifile">
<input type="file" id="fileToUpload" name="file" />
<span class="field-validation-error" id="spanfile"></span>
</li>
</ol>
<input type="submit" id="btnSubmit" value="Upload" />
}
At Controllers side :
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase file)
{
// Implementation
}

Displaying a message if ajaxform successfull or failed

I would like to upload a file without refreshing all the page. I know that uploading does not support classic ajax form. The trick is to use a classic form and to ajaxify it.
Here is my view:
#model .....
#using (Html.BeginForm("UploadImage", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", id = "uploadform" }))
{
<div class="editor-label"> #Html.LabelFor(model => model.Image) </div>
<div class="editor-field"> <input type="file" name="file" id="file" /> </div>
<button type="submit">
<span>Upload</span>
</button>
}
Here is my javascript:
$(document).ready(function() {
$('#uploadform').ajaxForm(function () {
alert("Thank you for your comment!");
});
});
Here is my controller:
[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase file)
{
// Add code here...
return RedirectToAction("EditProject");
}
When I submit a file, the action in the controller receive the information. BUT next nothing happened. The message 'Thank you for your comment!' is never displayed. I would like to display a message if the upload is successful of failed.
Thanks.
The UploadImage method in your Controller redirects to another action. You should return JSON with a message to be displayed.
public ActionResult UploadImage(HttpPostedFileBase file)
{
//processing code...
return Json(new { message = "Thank you..." });
}
And then in the View just alert the returned message.

Resources