Get text file as input in c# mvc - c#

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.

Related

How do i pass two text inputs into ActionResult method

I've been working on a large project for a few days. Its all finished except for this part. I'm trying to pass 2 text boxes into my home controller method.
I've tried to use "model." and "item." but with no luck. it always passes null
<p>
#Html.ActionLink("Display", "Home", FormMethod.Post)
</p>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div>
Month:<input type="text" name="Month" id="MonthInput">
Extra:<input type="text" name="Extra" id="ExtraInput"><br /><br />
<input type="submit" value="Add" class="btn btn-default"> <br> <br>
</div>
}
and in the home controller is
[HttpPost]
public ActionResult Display(String Month, String Extra)
{
if (ModelState.IsValid)
{
...
return RedirectToAction("Index");
}
return view;
}
I want it to pass whatever value is typed in the textboxes when the "Add" Button is clicked but it gives null
try this,
In View
#using (Html.BeginForm("Display", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div>
Month:<input type="text" name="Month" id="MonthInput">
Extra:<input type="text" name="Extra" id="ExtraInput"><br /><br />
<input type="submit" value="Add" class="btn btn-default"> <br> <br>
</div>
}
In Controller,
[HttpPost]
public ActionResult Display(SomeClass someClass)
{
if (ModelState.IsValid)
{
...
return RedirectToAction("Index");
}
return view;
}
Create Normal class name SomeClass, name as per your requirment,
public class SomeClass{
public string Month {get;set;}
public string Extra {get;set;}
}
the name attribute of inputs should match to properties of SomeClass, it will map automatically, you then can access the value by using someClass object
someClass.Month and someClass.Extra
In order to correctly map to the action's parameters, you must use the name attribute.
#using (Html.BeginForm("Display", "Home"))
{
#Html.AntiForgeryToken()
<div>
Month:<input type="text" name="Month" id="MonthInput">
Extra:<input type="text" name="Extra" id="ExtraInput"><br /><br />
<input type="submit" value="Add" class="btn btn-default">
</div>
}
Totally unrelated, but it seems you have 2 nested forms and one of them POSTs to a php page. Is that desired?
Also, remove the following code because it does not make any sense:
<p>
#Html.ActionLink("Display", "Home", FormMethod.Post)
</p>
To add on to the previous answer, I would suggest accepting the form as a FormCollection in the controller, because the form does not seem to be tied to the model:
[HttpPost]
public ActionResult Display(FormCollection collection)
{
if (ModelState.IsValid)
{
string month = collection["Month"];
string extra = collection["Extra"];
return RedirectToAction("Index");
}
return View();
}
namespace Your.Models
{
public class DisplayModel
{
public string Month {get;set;}
public string Extra {get;set;}
}
}
[HttpPost]
public ActionResult Display(DisplayModel model)
{
if (ModelState.IsValid)
{
string month = model.Month;
string extra = model.Extra;
return RedirectToAction("Index");
}
return View();
}
#using Your.Models
#model DisplayModel
#using (Html.BeginForm("Display", "Home", new { id="displayview" }))
{
#Html.AntiForgeryToken()
<div>
Month:<input type="text" name="Month" id="MonthInput">
Extra:<input type="text" name="Extra" id="ExtraInput"><br /><br />
<input type="submit" value="Add" class="btn btn-default">
</div>
}

Html.Hidden() generating blank values in HTML

I have a form on my view:
#using (Html.BeginForm("ClearData", "MemberPass", FormMethod.Post))
{
<div>
#foreach (var property in ViewData.ModelMetadata.Properties)
{
#Html.Hidden(property.PropertyName, property.Model)
}
</div>
<button>Clear</button>
}
and the following action methods:
public ActionResult Index()
{
MemberPassInfoViewModel memberPassInfoViewModel = new ServiceUtilities().GetEventDetails(DateTime.Now.Date);
return View("Index", memberPassInfoViewModel);
}
public ActionResult GetMemberPassInfo(MemberPassInfoViewModel currentMemberPassInfoValues)
{
MemberPassInfoViewModel updatedMemberPassInfoViewModel = new ServiceUtilities().GetMemberPassInfoViewModel(currentMemberPassInfoValues);
return View("Index", updatedMemberPassInfoViewModel);
}
public ActionResult ClearData(MemberPassInfoViewModel currentMemberPassInfoValues)
{
MemberPassInfoViewModel updatedMemberPassInfoViewModel = new ServiceUtilities().ClearData(currentMemberPassInfoValues);
return View("Index", currentMemberPassInfoValues);
}
In debug I can see that the model's two properties are present. However when I view the generated HTML, one of the properties has a blank value:
<input id="SearchCode" name="SearchCode" type="hidden" value="23" />
<input id="FullName" name="FullName" type="hidden" value="" />
I noticed that this could be fixed by replacing:
#Html.Hidden(property.PropertyName, property.Model)
with:
<input type="hidden" value="#property.Model" name="#property.PropertyName" />
Which generates:
<input type="hidden" value="23" name="SearchCode" />
<input type="hidden" value="Alex Robert" name="FullName" />
Why does the #Html.Hidden() method not work, but explicitly writing the <input> tag does work?

Adding an item to a virtual collection ASP.NET MVC

I am trying to post an item to a collection that belongs to another model.
This is the form in the view:
#using (Html.BeginForm("Create", "Comment", FormMethod.Post, new { enctype = "multipart/form-data", encoding = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="modal-body">
<div class="form-horizontal">
<input type="hidden" value="#Model.DeviceID" />
<div class="form-group">
<h5>Your name</h5>
<div class="col-md-10">
<input name="Author" />
</div>
</div>
<div class="form-group">
<h5>Comment</h5>
<div class="col-md-10">
<textarea name="Comment"></textarea>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="Submit" /> <!--Next</input>-->
</div>
}
and the controller code is set up as follows
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(string returnUrl, int devID, string Author, string text)
{
string url = this.Request.UrlReferrer.AbsolutePath;
Comment comment = new Comment();
if (ModelState.IsValid)
{
//db.Comments.Add(comment);
db.SaveChanges();
return Redirect(url);
}
return Redirect(url);
}
However this doesnt work because I cant set the model id of the item that is getting posted.
What is the Asp.net MVC way to add to a virtual collection that a model owns?
What I have noticed the names don't match in your controller. So you don't retrieve it well.
Change first this line:
<input name="Author" /> and <textarea name="Comment"></textarea>
By:
<input name="author" /> and <textarea name="comments"></textarea>
Could you change the parameters to match the name from the view.
public ActionResult Create(string returnUrl, int DeviceID, string author, string comments)
{
string url = this.Request.UrlReferrer.AbsolutePath;
Comment myComment = new Comment();
comment.DeviceID = DeviceID;
comment.Author = author;
comment.Comments= comments;// I presume your Comment class has thoses properties if not you can see at least the way you can deal with that
if (ModelState.IsValid)
{
db.Comments.Add(myComment);
db.SaveChanges();
return Redirect(url);
}
return Redirect(url);
}
I hope it will help. If you can show the code of your Comment model so I can edit that if it requires.

Null Exception in File Uploading in MVC4 Razor

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)]

Razor change label on HttpPost

new to razor, I have a label and a button
<form action="" method="post" enctype="multipart/form-data">
<label name="Mylabel">Test + #ViewData["MyLabelUpdate"]</label>
<input type="submit" id="MyBtn" Value="Change Label">
Now in the controller I have:
[HttpPost]
public ActionResult Index()
{
return RedirectToAction("Index");
}
How do I get the label to change using the actionresult method? Thanks
You have to make your controller look like this:
[HttpPost]
public ActionResult Index()
{
ViewBag.MyLabelUpdate = "whatever";
return RedirectToAction("Index");
}
And, your view:
<form action="" method="post" enctype="multipart/form-data">
<label name="Mylabel">Test + #ViewBag.MyLabelUpdate</label>
<input type="submit" id="MyBtn" Value="Change Label">

Categories

Resources