I am new to MVC3 and I would like to create a form with input column and file upload.
The problem comes when I try to do both thing at the same time.
Here is my code
...
[HttpPost]
public ActionResult About(string inputStr)
{
string local = inputStr;
string[] word = inputStr.Split(':');
return View();
}
[HttpPost]
public ActionResult GetFile(string inputStr, HttpPostedFileBase file)
{
string filename = file.FileName;
return RedirectToAction("About");
}
These two are my controllers
#using (Html.BeginForm("GetFile", "Home", (new { inputStr = "111" }), FormMethod.Post, new { enctype = "multipart/form-data" })){
<div class="editor">
<input type="file" name="file" />
<input type="submit" value="OK" id="submitFile" class="testingSubmit"/>
</div>
}
This code works well for uploading files, and sending string "111" to the controller.
Here is another jQuery function
$('.testingSubmit').click(function () {
var totalString="";
$('.editor-field :input').each(function () {
alert($(this).val());
totalString += $(this).val().toString() + ":";
});
$('form').submit();
/* $.post("About", { inputStr: totalString}, function (data) {
});*/
});
Here, what I am trying to do is the get the user input and put it on string totalString.
I was able to post the totalString to the controller by using $.post
My questions are:
1. Am i on the right track? i.e. Is that possible to do those two tasks together with one post?
2. If not, what are the possible solution for this?
Thank you very much for your attention and hopefully this can be solved!
I think something like this should work:
#using (Html.BeginForm("GetFile", "Home", (new { inputStr = "111" }), FormMethod.Post, new { #id = "frmGetFile", enctype = "multipart/form-data" })){
<div class="editor">
<input type="file" name="file" />
<input type="hidden" name="totalString" id="totalString"/>
<input type="submit" value="OK" id="submitFile" onclick="submitGetFileForm()" class="testingSubmit"/>
</div>
}
JavaScript:
function submitGetFileForm(e)
{
e.preventDefault();
var total = //build your total string here
$('#totalString').val(total);
$('#frmGetFile').submit();
}
Controller:
[HttpPost]
public ActionResult GetFile(string totalString, HttpPostedFileBase file)
{
// your action logic..
}
Related
I have to pass hidden filed values to controller action. So I have tried in the following way, but I am getting null values.
I have tried both methods i.e formcollection and viewmodel concept
Controller
public ActionResult MapIcon()
{
Hidden hd = new Hidden();
return View(hd);
}
[HttpPost]
public ActionResult MapIcon(Hidden hidden)
{
var value=hidden.hiddevalue;//null
FormCollection col = new FormCollection();
var value = col["hidden1"];
// string value = mycontroler.ControlName;
return View(hidden);
}
View
#model SVGImageUpload.Models.Hidden
Razor view:#using (Html.BeginForm(new { id = "postform" }))
{
<input type="hidden" id="" value="7" name="hidden1" />
<input type="hidden" id="" value="7" name="hidden2"/>
<input type="submit" value="Match"/>
}
Viewmodel
public class Hidden
{
public string hiddevalue { get; set; }
}
Try this, In Razor view:
#using (Html.BeginForm(new { id = "postform" }))
{
#Html.HiddenFor(m=>m.hiddevalue)
<input type="submit" value="Match"/>
}
It seems to me like you are trying to get multiple values into the POST controller. In that case, and by your exam, the value from the hidden input is enough. In that case, you can setup your controller as so:
public ActionResult Index()
{
Hidden hd = new Hidden();
return View(hd);
}
[HttpPost]
public ActionResult Index(IEnumerable<string> hiddens)
{
foreach (var item in hiddens)
{
//do whatter with item
}
return View(new Hidden());
}
and as for your view, simple change it in order to bind to the same name "hiddens" as so:
#using (Html.BeginForm(new { id = "postform" }))
{
<input type="hidden" value="7" name="hiddens" />
<input type="hidden" value="2" name="hiddens" />
<input type="submit" value="Match" />
}
Hope this serves what you are looking forward to.
if your hidden value is static.Than try this
View
#using (Html.BeginForm(new { id = "postform" }))
{
#Html.HiddenFor(m=>m.hiddevalue)
<input type="hidden" id="" value="7" name="hidden1" />
<input type="hidden" id="" value="7" name="hidden2"/>
<input type="submit" value="Match"/>
}
Controller
[HttpPost]
public ActionResult MapIcon(Hidden hidden, string hidden1, string hidden2)
{
var hiddenvalue = hidden.hiddevalue;
var hiddenvalue1 = hidden1;
var hiddenvalue2 = hidden2;
var value=hidden.hiddevalue;//null
FormCollection col = new FormCollection();
var value = col["hidden1"];
// string value = mycontroler.ControlName;
return View(hidden);
}
Script
$(document).ready(function () {
$('#hiddevalue').val("Jaimin");
});
Anyone know of any step by step tutorials on how to upload/display images from a database using Entity Framework? I've checked out code snippets, but I'm still not clear on how it works. I have no code, because aside from writing an upload form, I'm lost. Any (and I mean any) help is greatly appreciated.
On a sidenote, why don't any books cover this topic? I have both Pro ASP.NET MVC 4 and Professional MVC4, and they make no mention of it.
Have a look at the following
#using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" class="submit" />
}
your controller should have action method which would accept HttpPostedFileBase;
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(
Server.MapPath("~/images/profile"), pic);
// file is uploaded
file.SaveAs(path);
// save the image path path to the database or you can send image
// directly to database
// in-case if you want to store byte[] ie. for DB
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}
}
// after successfully uploading redirect the user
return RedirectToAction("actionname", "controller name");
}
Update 1
In case you want to upload files using jQuery with asynchornously, then try this article.
the code to handle the server side (for multiple upload) is;
try
{
HttpFileCollection hfc = HttpContext.Current.Request.Files;
string path = "/content/files/contact/";
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
string fileName = "";
if (Request.Browser.Browser == "IE")
{
fileName = Path.GetFileName(hpf.FileName);
}
else
{
fileName = hpf.FileName;
}
string fullPathWithFileName = path + fileName;
hpf.SaveAs(Server.MapPath(fullPathWithFileName));
}
}
}
catch (Exception ex)
{
throw ex;
}
this control also return image name (in a javascript call back) which then you can use it to display image in the DOM.
UPDATE 2
Alternatively, you can try Async File Uploads in MVC 4.
Here is a short tutorial:
Model:
namespace ImageUploadApp.Models
{
using System;
using System.Collections.Generic;
public partial class Image
{
public int ID { get; set; }
public string ImagePath { get; set; }
}
}
View:
Create:
#model ImageUploadApp.Models.Image
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm("Create", "Image", null, FormMethod.Post,
new { enctype = "multipart/form-data" })) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Image</legend>
<div class="editor-label">
#Html.LabelFor(model => model.ImagePath)
</div>
<div class="editor-field">
<input id="ImagePath" title="Upload a product image"
type="file" name="file" />
</div>
<p><input type="submit" value="Create" /></p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Index (for display):
#model IEnumerable<ImageUploadApp.Models.Image>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.ImagePath)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ImagePath)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ID }) |
#Ajax.ActionLink("Delete", "Delete", new {id = item.ID} })
</td>
</tr>
}
</table>
Controller (Create)
public ActionResult Create(Image img, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
file.SaveAs(HttpContext.Server.MapPath("~/Images/")
+ file.FileName);
img.ImagePath = file.FileName;
}
db.Image.Add(img);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(img);
}
Hope this will help :)
<input type="file" id="picfile" name="picf" />
<input type="text" id="txtName" style="width: 144px;" />
$("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;
var file = document.getElementById("picfile").files[0];
formData.append("FileUpload", file);
formData.append("Name", Name);
$.ajax({
type: "POST",
url: '/Category_Subcategory/Save_Category',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (msg) {
alert(msg);
},
error: function (error) {
alert("errror");
}
});
});
[HttpPost]
public ActionResult Save_Category()
{
string Name=Request.Form[1];
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
}
}
I want to pass image as well as some data from view to controller on submit button click.
Bellow is my code
My View
#using (Html.BeginForm("AccountPhotoPost", "Post", FormMethod.Post, new {enctype = "multipart/form-data", accountId = Model.accountId }))
{
<text>Post Photo : </text> <input type="file" name="file" id="file" />
<input type="submit" value="Post Photo" id="saveButton"/>
}
My controller action
[HttpPost]
public ActionResult AccountPhotoPost(HttpPostedFileBase file, long accountId)
{
}
Here problem is that as it is FormMethod.Post , data is not passed from view to controller & if I remove this then data is passed but image is not passed.
How can I send both together ?
Try this
#model SomeModel
#using (Html.BeginForm("AccountPhotoPost", "Post", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
<text>Post Photo : </text> <input type="file" name="file" id="file" />
#Html.HiddenFor(model => model.accountId )
<input type="submit" value="Post Photo" id="saveButton"/>
}
in Controller
[HttpPost]
public ActionResult AccountPhotoPost(SomeModel model ,HttpPostedFileBase file)
{
var Id = model.accountId;
}
Try This
HttpPostedFileBase hpf = Request.Files["file"] as HttpPostedFileBase;
var httpPostedFileBase = Request.Files["file"];
if (httpPostedFileBase != null && (hpf != null && httpPostedFileBase.ContentLength > 0))
{
var postedFileBase = Request.Files["file"];
if (postedFileBase != null)
{
fileName = postedFileBase.FileName;
BinaryReader reader = new BinaryReader(postedFileBase.InputStream);
byte[] attachmentBinary = reader.ReadBytes((int)postedFileBase.ContentLength);
hcUserReview.AttachmentByteValue = attachmentBinary;
hcUserReview.FileName = fileName;
}
}
This is View
ViewPage.cshtml
#using (Html.BeginForm("Display", "Home", FormMethod.Post))
{
<div>Name:<a>#ViewBag.st</a><br /></div>
<input type="submit" value="Submit" />
<br />
}
My jquery for editing #ViewBag.st
<script type="text/javascript">
$(document).ready(function () {
$('a').click(function () {
var textbox = $('<input id="Text1" type="text" size="100" />')
var oldText = $(this).text();
$(this).replaceWith(textbox);
textbox.blur(function () {
var newValue = $(this).val();
$(this).replaceWith($('<a>' + newValue + '</a>'));
});
textbox.val(oldText);
});
});
</script>
My controller methos is
public ActionResult Viewdetails()
{
User ur = new User();
ur.Name = "Danny";
ViewBag.st = ur.Name;
return View();
}
And my Model Class is
User.cs
public class User
{
//public string name { get; set; }
private string m_name = string.Empty;
public string Name
{
get
{
return m_name;
}
set
{
m_name = value;
}
}
}
After editing #ViewBag.title i want to store that value and pass to next View Can anyone suggest some ideas
I would recommend you to not use ViewBag at all.
So in your javascript you could give your textbox the same name as your User model property (Name):
var textbox = $('<input type="text" size="100" name="Name" />');
and then have the 2 controller actions (GET and POST):
public ActionResult Viewdetails()
{
User ur = new User();
ur.Name = "Danny";
return View(ur);
}
[HttpPost]
public ActionResult Display(User model)
{
return View(model);
}
And inside Viewdetails.cshtml:
#model User
#using (Html.BeginForm("Display", "Home", FormMethod.Post))
{
<div>Name: <a>#Model.Name</a><br /></div>
<input type="submit" value="Submit" />
<br />
}
And inside the Display.cshtml:
#model User
<div>You have selected: #Model.Name</div>
I have code in View:
#using (Html.BeginForm("MyAction", "MyController")
{
<input type="text" id="txt" />
<input type="image" src="/button_save.gif" alt="" />
}
How can I pass value of txt to my controller:
[HttpPost]
public ActionResult MyAction(string text)
{
//TODO something with text and return value...
}
Give your input a name and make sure it matches the action's parameter.
<input type="text" id="txt" name="txt" />
[HttpPost]
public ActionResult MyAction(string txt)
Add an input button inside of your form so you can submit it
<input type=submit />
In your controller you have three basic ways of getting this data
1. Get it as a parameter with the same name of your control
public ActionResult Index(string text)
{
}
OR
public ActionResult Index(FormsCollection collection)
{
//name your inputs something other than text of course : )
var value = collection["text"]
}
OR
public ActionResult Index(SomeModel model)
{
var yourTextVar = model.FormValue; //assuming your textbox was inappropriately named FormValue
}
I modified Microsoft MVC study "Movie" app by adding this code:
#*Index.cshtml*#
#using (Html.BeginForm("AddSingleMovie", "Movies"))
{
<br />
<span>please input name of the movie for quick adding: </span>
<input type="text" id="txt" name="Title" />
<input type="submit" />
}
//MoviesController.cs
[HttpPost]
public ActionResult AddSingleMovie(string Title)
{
var movie = new Movie();
movie.Title = Title;
movie.ReleaseDate = DateTime.Today;
movie.Genre = "unknown";
movie.Price = 3;
movie.Rating = "PG";
if (ModelState.IsValid)
{
db.Movies.Add(movie);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return RedirectToAction("Index");
}
}