I don't suppose anyone's clued up on this? The documentation is terrible and far outdated (the best resource I could find was dated 2006).
My form:
<form action="DoCreate.rails" method="post">
${FormHelper.LabelFor("master.Name", "Name", {"class":"label"})}
${FormHelper.TextField("master.Name", {"class":"text-input full-width"})}
${FormHelper.LabelFor("masterFile", "File", {"class":"label"})}
<input type="file" id="masterFile" name="masterFile" />
<div class="edit-controls">Back | <input type="submit" value="Create" /></div>
</form>
My controller action:
public void DoCreate(Master master, HttpPostedFile masterFile)
{
try
{
Bus.Master.Create(master);
if (masterFile != null)
{
masterFile.SaveAs(#"C:\" + masterFile.FileName);
}
RedirectToAction("Index");
}
catch (ApplicationException e)
{
PropertyBag["error"] = e.Message + "<br />" + e.StackTrace;
Create();
RenderView("Create");
}
}
I followed this guide also with no avail as it doesn't tell you what to do on the actual HTML page.
Looks like the problem is with the declaration of the form.
When uploading files, you should use add another attribute to the form element: enctype="multipart/form-data"
Related
In Asp.Net Core, it appears that they have done away with the Request.Content.ReadAsMultipartAsync functionality in favor of the IFormFile.
This makes uploading where you have an actual file a LOT easier, however, I have a use case where I need to upload a file to browser memory, process it, then send it as part of the multi-form data in the body. IFormFile cannot see this as there is no actual file to read. It only works if you have a filename property on the Content-Disposition and an actual file on the client to upload.
In my Asp.Net 4 app, I could read the mutlipart data in the body whether that was sent between boundaries or as an attached file.
How do I accomplish this in .Net Core?
What I figured out is that the multipart values are passed into the HttpRequest.Form as an array of key/value pairs. The "name" value on the body's multipart determines the name of the key.
I created a helper method that grabs both files and form values.
public static List<FileModel> GetFileModelsFromRequest(HttpRequest request)
{
var fileModels = new FileModels();
foreach (var formField in request.Form)
{
// Form data
var fileModelText = formField.Value;
... process and add to the FileModel list
}
if (request.Form.Files != null && request.Form.Files.Count > 0)
{
foreach (var file in request.Form.Files)
{
using (MemoryStream ms = new MemoryStream())
{
// File data
formFile.CopyTo(ms);
}
... process and add to the FileModel list
}
}
return fileModels;
}
I have done it this way. when I had to capture image from webcam and process (show that image in browser) it in browser memory and later on post that image using a form.
public IActionResult Index()
{
var files = HttpContext.Request.Form.Files;
if (files != null)
{
foreach (var file in files)
{
var fileName = file.Name;
}
}
return View();
}
I used a JS library Webcam.js to capture image from webcam and show that image on the same page. and once a user is satisfied with the image, s/he can upload the image to the server.
<!-- Configure settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach('#camera');
</script>
<!-- handle snapshot and displaying it locally -->
<script language="JavaScript">
function take_snapshot() {
// take snapshot and get image data
Webcam.snap(function (data_uri) {
// display results in page
document.getElementById('imageResults').innerHTML =
'<img src="' +
data_uri +
'"/>';
Webcam.upload(data_uri,
'/Default/Index',
function (code, text) {
console.log('Photo Captured');
});
});
}
</script>
<div class="panel panel-default">
<div class="panel-heading">Camera</div>
<div class="panel-body">
<div id="camera"></div>
<!-- A button for taking snaps -->
<form>
<input type="button" class="btn btn-success" value="Take Snapshot" onClick="take_snapshot()">
</form>
<div class="panel panel-default">
<div class="panel-heading">Captured Image</div>
<div class="panel-body">
<div id="imageResults">captured image will appear here...</div>
</div>
<br />
<br />
</div>
let me know if this is what you are looking for.
I am currently working laravel 5 project. I am trying to do file upload but i found that i am not able to get $_FILES in my controller function. It shows only [] when i write dd($_FILES); in my controller function.
VIEW CODE:
{!!Form::open(['url'=>'admin','id'=>'MyUploadForm'])!!}
<input name="fileupload" id="fileupload" type="file" />
<input type="submit" id="submit-btn">
{!!Form::close()!!}
ROUTE CODE:
Route::get('admin', 'CouponcodefileController#index');
Route::post('admin', 'CouponcodefileController#uploadfile');
CONTROLLER FUNCTION:
public function uploadfile() {
dd($_FILES);
}
Please guide in this. Thanks.
Try:
"files" => true
View
{!!Form::open(['url'=>'admin','id'=>'MyUploadForm', 'method'=>'POST', 'files'=>true])!!}
<input name="fileupload" id="fileupload" type="file" />
<input type="submit" id="submit-btn">
{!!Form::close()!!}
Controller
public function uploadfile() {
$file = \Input::file('fileupload'));
// $file = \Request::file('fileupload'));
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
dd($file);
}
http://api.symfony.com/2.6/Symfony/Component/HttpFoundation/File/UploadedFile.html
Do it the Laravel way (5.1):
CONTROLLER FUNCTION:
public function uploadfile(Request $request) {
// Laravel 5.0: $file = Request::file('fileupload');
$file = $request->file('fileupload');
dd($file);
}
https://laravel.com/docs/5.1/requests#files
I am kind of lost on how to do this in my view.
I want to add the quantity. Right now, it adds but how do I get the input value into my ajaxlink?
My controller is using session to add.
<input id="quantity" type="text" value="1" class="span1">
<div id="cart-text">
<?php echo CHtml::ajaxLink(' Add ',
Yii::app()->createUrl('controller/basketAjax',array('id'=>$_GET['id'])),
array('success'=>'function(data){...
controller:
$session=new CHttpSession;
$session->open();
if (!isset(Yii::app()->session['cart']))
{
$quantity = 1;
$session->add('cart',array(
'product_id.'.$id=>array("id"=>$id,
'quantity'=>$quantity)
));
}
else
{
$cart = Yii::app()->session['cart'];
$array = $cart['product_id.'.$id];
if (isset($array)){
$array['quantity']=$array['quantity']+1;
} else {
$t = array('product_id.'.$id=>array("id"=>$id,'quantity'=>$quantity));
array_push($cart,$t);
}
$session->add('cart', $products);
}
you can do this by using keyup function of jquery. First set the id of link as "mylink". Compute the url by using createUrl.
<script type="text/javascript" >
$("#quantity").keyup(function(){
var url=<?php echo Yii::app()->createUrl('controller/basketAjax') ?>;
$("#mylink").attr("href","");
$("mylink").attr("href",url +$(this).val());
});
</script>
Now i explain whats happening above. first i catch the event keyup on input you are using. It will be called each time you press a key on input. Now url=<?php echo Yii::app()->createUrl('controller/basketAjax') ?>; this code is returning you the base url to your action without any parameters being passed.this line $("#mylink").attr("href",""); will set the href of your link to " "( means nothing). Now this line $("mylink").attr("href",url +$(this).val()); is appending the value of the input you are getting from the input.
Remember you have to put the separator in between like
$("mylink").attr("href",url+"/" +"id"+"/"+$(this).val());
Above i have assumed that the href in your case looks like "projectname/index.php/controller/action/id/something". Thats y i have used separators in between but you can customize it according to your needs.
ajaxLink will not work (from what I know), just build it the old fashion way with jquery. Your best solution is actually to put it in a form and submit the form. Something like
<?php
Yii::app()->clientScript->registerCoreScript('yiiactiveform');
$form=$this->beginWidget('CActiveForm', array('action'=>Yii::app()->createUrl('cart/addProduct')));?>
<input type="text" name="quantity" value="1">
<input type="hidden" name="Product_id" value="<?php echo $model->id;?>">
<?php echo CHtml::ajaxSubmitButton('Save',CHtml::normalizeUrl(array('cart/addProduct','render'=>true)),
array(
'dataType'=>'json',
'type'=>'post',
'success'=>'function(data) {
if(data.status=="success"){
$("#formResult").html("form submitted successfully.");
}
else{
$.each(data, function(key, val) {
$("#user-form #"+key+"_em_").text(val);
$("#user-form #"+key+"_em_").show();
});
}
}',
)); ?>
<?php $this->endWidget(); ?><!-- .contact -->
Sorry for the indenting, hard to indent properly here.
I'm working on asp.Net MVC4 project, and I need to create ActionLink for each element of a list.
Here is what I have done:
<div class="display-field" id="kalamsDiv">
#foreach(Elections.Domain.Models.Kalam kalam in Model.Kalams)
{
Html.ActionLink(#kalam.Name, "Details", "Kalam", #kalam.KalamID, "");
<br />
}
</div>
And in the model of the view I have a list of "Kalam" object:
public virtual ICollection<Kalam> Kalams { get; set; }
But I'm not seeing any ActionLink, the div is empty, I can only see the line breaks : <br />.
What is the mistake I'm making?
Thanks :)
Use # before Html.ActionLink and remove them before kalam variable. Create an anonymous object for routeValues and pass null for htmlAttributes.
<div class="display-field" id="kalamsDiv">
#foreach(Elections.Domain.Models.Kalam kalam in Model.Kalams)
{
#Html.ActionLink(kalam.Name, "Details", "Kalam", new { ID = kalam.KalamID }, null);
<br />
}
</div>
I'm currently building a website where I have to update two separate targets from a single Ajax.BeginForm. I got it working by using an additional container to container the two separate targets. As in:
Original Form
#model Mod1
#using (Ajax.BeginForm("LoadData", new AjaxOptions{UpdateTargetID = "Div1"}))
{
<select id="sel1" name="sel1" onchange="$(this.form).submit">
// ...
</select>
}
#using (Ajax.BeginForm("ProcessData", new AjaxOptions{UpdateTargetID = "Div2"}))
{
<div id="Div1"></div>
// ...
<input type="submit" value="GO!" />
}
Code File
public ActionResult LoadData(int sel1)
{
// loading data from database
return PartialView(mod1);
}
Partial View
#model Mod2
<select id="sel2" name="sel2">
#foreach (var item in Model.SelectItems)
{
<option value="#item.Value">#item.Text</option>
}
</select>
#foreach (var item in Model.CheckBoxItems)
{
<label>#item.Text<input type="checkbox" id="chk1" name="chk1" value="#item.Value"></label>
}
For the processing method, I have tried:
public ProcessData(Mod1 mod1, string[] chk1, int sel2)
However I am unable to retrieve the values for either chk1 or sel2 upon form submission. examination of chk1 and sel2 in Debug mode, chk1 is null while sel2 is 0 (no such value in the select options). Can anyone please offer some insight into the reason for this and also how I can go about solving it. Thank you in advance.
If I understand you correctly you can do what you want y having two submit buttons on the same form, each calling a separate action method. That way each submit button will have access to all the fields in the form. For a detailed explanation of how you can do that see my answer here:
How to use ajax link instead of submit button for form?
Edit
In response to comment: the action method LoadData should return a partial view that contains the other two controls and have the whole begin form included in it:
#using (Ajax.BeginForm("LoadData", new AjaxOptions{
UpdateTargetID = "Div1",
InsertionMode = InsertionMode.Replace
}))
{
<select id="sel1" name="sel1" onchange="$(this.form).submit">
// ...
</select>
}
<div id="Div1">
</div>
<div id="Div2">
</div>
Move this to another partial view:
#using (Ajax.BeginForm("ProcessData", new AjaxOptions{UpdateTargetID = "Div2"}))
{
// ...
<input type="submit" value="GO!" />
}