Null Exception in File Uploading in MVC4 Razor - c#

I have created the following view, with having file upload and submit button.
#using (Html.BeginForm("FileUpload", "Home",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input name="uploadFile" type="file" />
<input type="submit" value="Upload File" id="btnSubmit" />
}
I have also created the action method in Controller but it gives the null at the "uploadFile"
[HttpPost)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}

Can u try Name with same as uploadFile
In your Page:
#using (Html.BeginForm("FileUpload", "Home",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input id="uploadFile" name="uploadFile" type="file" />
<input type="submit" value="Upload File" id="btnSubmit" />
}
As per #Willian Duarte comment : [HttpPost]
In your Code behind:
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase uploadFile) // OR IEnumerable<HttpPostedFileBase> uploadFile
{
//For checking purpose
HttpPostedFileBase File = Request.Files["uploadFile"];
if (File != null)
{
//If this is True, then its Working.,
}
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
See here Same question like yours.,
Code project Article about the File upload.,

Try to use (on controller):
var file = System.Web.HttpContext.Current.Request.Files[0];

create a model and bind it to your view that controller will also expect:
Controller:
//Model (for instance I've created it inside controller, you can place it in model
public class uploadFile
{
public HttpPostedFileBase file{ get; set; }
}
//Action
public ActionResult Index(uploadFile uploadFile)
{
if (uploadFile.file.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.file.FileName));
uploadFile.file.SaveAs(filePath);
}
return View();
}
View
#model sampleMVCApp.Controllers.HomeController.uploadFile
#using (Html.BeginForm("FileUpload", "Home",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(m => m.file, new { type = "file"});
<input type="submit" value="Upload File" id="btnSubmit" />
}
Tested Solution!
HTH :)

Use the following in the controller:
var file = System.Web.HttpContext.Current.Request.Files[0];
Use HttpPost instead of [AcceptVerbs(HttpVerbs.Post)]

Related

Get text file as input in c# mvc

I want to get the text file as input but I am getting only null value...
public ActionResult add_content()
{
return View();
}
[HttpPost]
public ActionResult add_content(HttpPostedFileBase d)
{
return View();
}
HTML:
<form action="http://localhost:49416/g1/add_content" method="post">
<input type="file" name="d" />
<input type="submit" name=" add content" />
</form>
I have included the screenshot with breakpoint
You can try this:
Controller:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
return View();
}
View:
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<label for="file"> Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" />
}
You were missing the enctype = "multipart/form-data"
Also it is important to note that input name must be the same in controller.

asp.net mvc submit doesnt hit actionresult method

would you mind to help me and say what I am doing wrong? I cannot spot the error and consequently after clicking the submit button, the HttpPost ActionResult method is not being hit?
Controller
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(testModel model)
{
if (ModelState.IsValid == true)
{
using (testRepository repository = new testRepository())
{
}
}
return View();
}
And the View
#using (Html.BeginForm("Index", "Test", FormMethod.Post, new {autocomplete="off" }))
{
<fieldset>
#Html.LabelFor(m => m.testValue)
#Html.TextBoxFor(m => m.testValue)
<input type="submit" value="Submit" />
</fieldset>
}

Ajax.BeginForm send parameters to controller

I have following Ajax.BeginForm on viewpage
using (Ajax.BeginForm("Financing_Product_Feature_Upload", "FileUpload", new { productid = #ViewBag.Product_ID }, new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data"}))
{
#Html.AntiForgeryToken()
<input type="file" name="files"> <input type="submit" value="Upload File to Server">
}
then I have following controller method in FileUpload controller class
[HttpPost]
public ActionResult Financing_Product_Feature_Upload(HttpPostedFileBase file, string productid)
{
but once I click above submit button its not directing to Financing_Product_Feature_Upload controller method
MVC serialization works on name attributes. Name of the form control needs to match with MVC controller action parameters. In your case, I guess, you should be getting an error in browser console when you hit "Submit" button saying "there is no matching action found on contoller FileUpload" or something which gives that meaning.
#using (Ajax.BeginForm("Financing_Product_Feature_Upload", "FileUpload", new { productid = #ViewBag.Product_ID }, new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<input type="file" name="files"> <input type="submit" value="Upload File to Server">
}
public class FileUploadController : Controller
{
[HttpPost]
public ActionResult Financing_Product_Feature_Upload(HttpPostedFileBase files, string productid)
{
// Action code goes here
}
}
try add # in enctype
using (Ajax.BeginForm("Financing_Product_Feature_Upload", "FileUpload", new { productid = #ViewBag.Product_ID }, new AjaxOptions() { HttpMethod = "POST" }, new { #enctype = "multipart/form-data"}))
{
#Html.AntiForgeryToken()
<input type="file" name="file"> <input type="submit" value="Upload File to Server">
}
Add # before using:
#using (Ajax.BeginForm("Financing_Product_Feature_Upload", "FileUpload", new { productid = ViewBag.Product_ID }, new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data"}))
{
#Html.AntiForgeryToken()
<input type="file" name="files"> <input type="submit" value="Upload File to Server">
}
And rename the HttpPostedFileBase file to files because this is your file input name.

Sending a phrase (variable) from searcher (from view) to controller, asp.net mvc

I'm trying to create searcher in asp.net. I'm so green about it. I'm trying to create in view and send to controller variable, which has text written in searcher. In that moment, I have smth like that -->
My question is, where and how create and send variable and give her data written in searcher?
Layout
form class="navbar-form navbar-left" role="search">
#using (Html.BeginForm("Index", "Searcher", FormMethod.Post, new { phrase = "abc" }))
{
<div class="form-group">
<input type="text" class="form-control" placeholder="Wpisz frazę...">
</div>
<button type="submit" class="btn btn-default">#Html.ActionLink("Szukaj", "Index", "Searcher")</button>
}
</form>
Controller
public class SearcherController : ApplicationController
{
[HttpGet]
public ActionResult Index(string message)
{
ViewBag.phrase = message;
getCurrentUser();
return View();
}
}
View
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<ul>
<li>#ViewBag.message</li>
</ul>
You're missing a key part of MVC -> the Model.
Let's create one first:
public class SearchModel
{
public string Criteria { get; set; }
}
Then let's update your "Layout" view (don't know why you had a form in a form?):
#model SearchModel
#using (Html.BeginForm("Index", "Searcher", FormMethod.Post, new { phrase = "abc" }))
{
<div class="form-group">
#Html.EditorFor(m => m.Criteria)
</div>
<button type="submit" class="btn btn-default">#Html.ActionLink("Szukaj", "Index", "Searcher")</button>
}
Then your action that serves that view:
[HttpGet]
public ActionResult Index()
{
return View(new SearchModel());
}
Then your post method would be:
[HttpPost]
public ActionResult Index(SearchModel model)
{
ViewBag.phrase = model.Criteria;
getCurrentUser();
return View();
}

MVC submit button not firing

I am using ASP.net MVC 4 with the Razor engine.
I have a page (Index.cshtml) and a controller (HomeController.cs)
I am trying to hook up my submit button to an Action Result in my controller - however i can't seem to get it to fire.
My HTML :
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post))
{
<div class="main-Background">
******lots of other html here*******
<button type="submit" id="btnSave">Save</button>
</div>
}
My Controller :
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
[HttpPost]
public ActionResult SubmitForm()
{
return View();
}
}
At the moment i havn't implemented a model to pass the values through to the controller, i just wanted to see if i could get the ActionResult SubmitForm to fire.
I have tried #using (Html.BeginForm()) with no parameters, i have also tried including [HttpPost] above my ActionResult, without any luck.
Edit i have also tried using <input type="submit" id="btnSave">Save</input> instead of a button.
Not sure where i am going wrong
It turns out that jQuery was stopping the ActionResult from being hit.
I had a button click event which was "eating up" the ActionResult functionality. I solved this by calling my ActionResult using Ajax.
You dont need to use "-Controller" suffix. Use just Home instead of HomeController, MVC will convert it for you.
Use
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post, new { id = "submitForm" }))
instead of
#using (Html.BeginForm("SubmitForm", "HomeController", FormMethod.Post, new { id = "submitForm" }))
Full codes
view
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post, new { id = "submitForm" }))
{
<div class="main-Background">
******lots of other html here*******
<input type="submit" id="btnSave">Save</input>
</div>
}
And controller
[HttpPost]
public ActionResult SubmitForm()
{
return View();
}
View:
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post))
{
<div class="main-Background">
******lots of other html here*******
<button type="submit" id="btnSave">Save</button>
</div>
}
Controller:
[HttpPost]
public ActionResult SubmitForm()
{
return View();
}
May be the problem is occurred because of other HTML inside your div so check it out. Otherwise it works perfectly.
You need to add Html.BeginForm with the parameters. Here is an example:
ActionName – Name of the Action. In this case the name is Create.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
http://localhost:60386//Home/Create
#using (Html.BeginForm("Create", "Home", FormMethod.Post))
{
#Html.EditorFor(model => model.FirstName)
<input type="submit" value="Create"/>
}
HomeController.cs:
[HttpPost]
public ActionResult Create(Person person)
{
if (ModelState.IsValid)
{
db.Persons.Add(person);
db.SaveChanges();
return RedirectToAction("Create");
}
return View(person);
}
TL;DR
I had [Required] data attributes on my view model preventing the submit from working when the form wasn't filled.
I had two submit buttons in my MVC code, one for Submit, the other for Cancel.
Both buttons were firing correctly on data entry, but neither when nothing was entered.
It took me a bit to realize that my view model had [Required] field validations in place!
View:
#using (Html.BeginForm(actionName: "Index", controllerName: "User", method: FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.TextBoxFor(m => m.PhoneNumber)
...
<input type="submit" name="submitAction" value="Verify" />
<input type="submit" name="submitAction" value="Cancel" />
}
ViewModel:
public class UserViewModel
{
[Required]
[MaxLength(10)]
public string PhoneNumber { get; set; }
[Required]
...
}
Controller Method:
[HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult Index(UserViewModel viewModel, string submitAction)
{
switch(submitAction)
{
case "Verify": ...
case "Cancel": ...
}
}
Change this #using (Html.BeginForm("SubmitForm", "HomeController", FormMethod.Post, new { id = "submitForm" }))
to
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post, new { id = "submitForm" }))
Explanation : No need to suffix Controller anywhere, it being accepted by default
and in the Controller
[HttpPost]
public ActionResult SubmitForm(string id)
{
return View();
}
Explanation : as the Form Method given by you is Post so need to include [HttpPost] before the Action and the parameter you were passing was missing in the action method

Categories

Resources