I use Ajax.Beginform menthod to upload file, but it not work, please help me.
File Create.cshtml :
#using (Ajax.BeginForm("UpLoadFile", "KG", new AjaxOptions { HttpMethod = "POST" }, new { enctype = "multipart/form-data", #id = "form-uploadfile" }))
{
<input type="file" name="fileupload" id="fileupload" />
<input type="submit" value="UpLoad" />
}
Controller in server side
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase fileupload)
{
if (fileupload != null)
{
// Verify that the user selected a file
if (fileupload != null && fileupload.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(fileupload.FileName);
// TODO: need to define destination
var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
fileupload.SaveAs(path);
}
}
return Json(new { success = true });
}
parameter fileupload alway null, i reference many post but still yet solve problem :(
Sorry,My English is very bad
Related
I have an issue whereby the ajax form in my login popup loads the homepage into a partial view on success. When there is a failure or validation issue the partial view is reloaded but it should not when login is successful.
Ajax form in Navbar:
<li class="login">
<span>Login</span>
#using (Ajax.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "login_box"
}, new { id = "login_box" }))
{
#Html.Action("loginform", "Home")
}
</li>
This then loads the content of the form from a shared partial view name _loginpartial (shortened):
<div class="login_box_lower">
<p class="login_box_or">or</p>
<p class="login_sign_in">Sign in</p>
<div style="position:relative;">
#Html.EditorFor(m => m.Email, new { htmlAttributes = new { placeholder = "Email", maxlength = "30", #class = "login_username clearable" } })
<span class="login_username_icon"></span>
</div>
<div style="position:relative;">
#Html.EditorFor(m => m.Password, new { htmlAttributes = new { placeholder = "Password", maxlength = "18", #class = "login_pw clearable" } })
<span class="login_pw_icon"></span>
</div>
<div class="rememberbox" >
#Html.CheckBoxFor(m => m.RememberMe, new { #class = "remembercheck" })
#Html.LabelFor(m => m.RememberMe)
</div>
<input type="submit" class="login_button" value="Log in" />
The controller action:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return PartialView("_LoginPartial", model);
}
// Require the user to have a confirmed email before they can log on.
var user = await UserManager.FindByNameAsync(model.Email);
if (user != null)
{
if (!await UserManager.IsEmailConfirmedAsync(user.Id))
{
string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account-Resend");
ViewBag.errorMessage = "You must have a confirmed email to log on. "
+ "The confirmation token has been resent to your email account.";
return View("Error");
}
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return PartialView("_LoginPartial", model);
}
}
The RedirectToLocal action is as per the default:
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
So as I see it if the login is successful and the returnUrl string is null then the home index view should be returned? Why is it only being returned in the partial view of the login popup?
Additionally my returnURL string generated at the start of the Ajax form doesn't seem to work, so if anyone could suggest to me where I am going wrong with that it would be very helpful. Thanks.
Does anyone has a clean suggestion of instantiate this jquery's useful library.
I need to submit files and manage the Json response from the server.
I always get none json response within the Js code. I have reviewed some articles mentioning it but the code doesn't fit to the purpose.
The situation is: I achieve the submition and saving in the database but the Json response never arrives.
Thanks in advance.
This is my view code:
<script type="text/javascript">
$("#formUplImg").fileupload({
dataType: "json",
url:'#Url.Action("CreateJson","ProductImage")',
done: function (e, data) {
alert(data.StatusMessage);
}
});
</script>
#using (Html.BeginForm("CreateJson", "ProductImage", FormMethod.Post, new { id = "formUplImg", enctype = "multipart/form-data", #class = "jqtransform" }))
{
#Html.ValidationSummary(true)
<div class="rowElem">
<input type="file" id="Content" name="Content" />
</div>
<div class="rowElem">
#Html.ValidationMessageFor(item => item.Content)
</div>
<div class="rowElem">#Html.JQueryUI().Button("Guardar imagen", ButtonElement.Button, ButtonType.Submit, new { id = "guardar_imagen" })</div>
}
This is my controller action code:
[HttpPost]
public ContentResult CreateJson(UploadedFileInfo fileInfo)
{
try
{
if (fileInfo.Content == null)
throw new Exception("Hubo problemas con el envĂo. Seleccione un archivo a subir");
var file = new TempDocument
{
CreatedBy = User.Identity.Name,
CreationTime = DateTime.Now,
FileName = fileInfo.Content.FileName,
MimeType = fileInfo.Content.ContentType,
Size = fileInfo.Content.ContentLength,
Content = new byte[fileInfo.Content.ContentLength]//Image content to save
};
fileInfo.Content.InputStream.Read(file.Content, 0, fileInfo.Content.ContentLength);//Reading image content into ProductImage object
DocumentsManager.StorePendingDocuments.Add(file);
DocumentsManager.SaveTempDocuments();//Store each document uploaded to: TempDocument Table
TempData["SuccessMsg"] = "The image was saved successfully";
var json = new JavaScriptSerializer().Serialize(new { Success = true, StatusMessage = "El objeto fue insertado correctamente" });
return Content(json, "application/json");
}
catch (Exception exception)
{
TempData["ErrorMsg"] = exception.Message;
var json = new JavaScriptSerializer().Serialize(new { Success = false, StatusMessage = exception.Message });
return Content(json, "application/json");
}
}
Use return type of Action as ActionResult and use:
`return Json(new { Result = "Success" });`
So that on success you will get Json object containing result value.
I want to use this star rating plugin in my MVC 4 application.
I have Rating table like this:
public class Rating
{
public int FromUserId { get; set; }
public int ToProductId { get; set; }
public int RateValue { get; set; }
}
I have an action like this:
public ActionResult SubmitRating(int fromUserId, int toProductId , int rateValue )
{
return View();
}
FromUserId is #WebSecurity.CurrentUserId and
ToProductId is Model.Id
I have problem with ajax. I need to send RateValue to action.
How can I send selected value to SubmitRating action in controller and reverse, to send back an answer from controller to view (to show selected value, to show any message to user etc.) ?
This does not work. How to write ajax code here?
$(function(){
$('#star-rating').rating(function(vote, event){
$.ajax({
url: "#Url.Action("SubmitRating", "MyController")",
type: "GET",
data: {rateValue : vote},
});
});
});
Let's assume some things:
your HTML has the product id:
<div id="star-rating" data-pid="#Model.Id">
<input type="radio" name="example" class="rating" value="1" />
<input type="radio" name="example" class="rating" value="2" />
<input type="radio" name="example" class="rating" value="3" />
<input type="radio" name="example" class="rating" value="4" />
<input type="radio" name="example" class="rating" value="5" />
</div>
so you can have a list of products instead only one product per page.
It's not a security practice to pass the user id if that's the same as the current logged in one, you could simple fetch the userid from the current session., so we would have in our controller:
public class ServicesController : Controller
{
public ActionResult RateProduct(int id, int rate)
{
int userId = WebSecurity.CurrentUserId;
bool success = false;
string error = "";
try
{
success = db.RegisterProductVote(userId, id, rate);
}
catch (System.Exception ex)
{
// get last error
if (ex.InnerException != null)
while (ex.InnerException != null)
ex = ex.InnerException;
error = ex.Message;
}
return Json(new { error = error, success = success }, JsonRequestBehavior.AllowGet);
}
}
this way you can easily call your rate like:
<script>
$(function () {
$('#star-rating').rating(function (vote, event) {
var anchor = $(event.currentTarget),
pid = anchor.closest(".ratting-item").data("pid"),
url = '#Url.Action("RateProduct", "Services")';
// show a loading div that would have a animated gif
$(".loading").show();
$.ajax({
url: url,
type: "GET",
data: { rate: vote, id: pid },
success: function (data) {
if (data.success) {
// all went well, here you can say Thank you
}
else {
// There must be an Exception error, let's show it
}
},
error: function (err) {
// the call thrown an error
},
complete: function () {
$(".loading").hide();
}
});
});
});
</script>
updated
$(this) does not return the correct element, so we need to use the event property that is passed along the call:
So we need to change to this:
var anchor = $(event.currentTarget),
pid = anchor.closest(".ratting-item").data("pid"),
url = '#Url.Action("RateProduct", "Services")';
a simple console.log($(this)) and then console.log(event); would tell you that, plus, if you fire Fiddler, you will see what's missing as well seeing the error on the returned call.
Project example on GIT
Here's the source code of this project working: https://github.com/balexandre/Stackoverflow-Question-14014091
Hi all i am working in mvc4 when writing a code for image optimization content showing the error i need to do this any body plz help me to solve this iam getting this error
here is my code:Controllers
public ActionResult Uploading(ImageModel model)
{
var uploadFolder = HostingEnvironment.MapPath("~/App_Data");
uploadFolder = Path.Combine(uploadFolder, DateTime.Now.ToString("yyyy/MM/dd/hh/mm/ss/fff"));
Directory.CreateDirectory(uploadFolder);
var streamProvider = new PreserveFilenameMultipartFileStreamProvider(uploadFolder);
Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
{
foreach (var uploadedFile in Directory.GetFiles(uploadFolder))
{
var medium = Path.Combine(uploadFolder, "medium-" + Path.GetFileName(uploadedFile));
var thumbnail = Path.Combine(uploadFolder, "thumb-" + Path.GetFileName(uploadedFile));
ImageTools.Resize(uploadedFile, thumbnail, 100, 100);
ImageTools.Resize(uploadedFile, medium, 50, 50);
}
return new HttpResponseMessage()
{
Content = new StringContent("File uploaded.")
};
});
return View("Upload", model);
}
and here is my index page :
#using (Html.BeginForm("Uploading", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="ImageUploaded" id="btnUpload" multiple="multiple" accept="image/*" />
<button type="submit" id="Upload">Upload</button>
<br />
//#Html.DisplayForModel(#ViewData["Time"]);
<label>#ViewData["Time"]</label>
}
here iam getting an error at Content :HTTPRequestBase doesnot contain defnation for content
Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
could any body help me to solve the problem thanks in advance
Please use the below line in your view:
#using (Html.BeginForm("Action Name", "Controller Name", FormMethod.Post, new { enctype = "multipart/form-data" }))
Because you are uploading the file, you are required to define the above line of code.
I have the ability to upload a file and save it to a directory. That is all good. I need to make an entry to my database with information about that file. So far I am not sure how to pass a value from the view to the controller in this particular case. I have tried to pass it as a method parameter but the value is not getting posted.
Here is my Razor form:
#using (Html.BeginForm("AjaxUpload", "Cases", FormMethod.Post, new { enctype = "multipart/form-data", id = "ajaxUploadForm" }))
{
<fieldset>
<legend>Upload a file</legend>
<label>File to Upload: <input type="file" name="file" />(100MB max size)</label>
<input id="ajaxUploadButton" type="submit" value="Submit" />
</fieldset>
}
<div id="attachments">
#Html.Partial("_AttachmentList", Model.Attachments)
</div>
Here is my jQuery to ajaxify the form:
$(function () {
$('#ajaxUploadForm').ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function () {
$('#ajaxUploadForm').block({ message: '<h1><img src="/Content/images/busy.gif" /> Uploading file...</h1>' });
},
success: function (result) {
$('#ajaxUploadForm').unblock();
$('#ajaxUploadForm').resetForm();
$.growlUI(null, result.message);
//$('#attachments').html(result);
},
error: function (xhr, textStatus, errorThrown) {
$('#ajaxUploadForm').unblock();
$('#ajaxUploadForm').resetForm();
$.growlUI(null, 'Error uploading file');
}
});
});
Here is the controller method:
public FileUpload AjaxUpload(HttpPostedFileBase file, int cid)
{
file.SaveAs(Server.MapPath("~/Uploads/" + file.FileName));
var attach = new Attachment { CasesID = cid, FileName = file.FileName, FileType = file.ContentType, FilePath = "Demo", AttachmentDate = DateTime.Now, Description = "test" };
db.Attachments.Add(attach);
db.SaveChanges();
//TODO change this to return a partial view
return new FileUpload { Data = new { message = string.Format("{0} uploaded successfully.", System.IO.Path.GetFileName(file.FileName)) } };
}
I would like cid to be passed to this method so that I can insert a record into the database.
You could include it as a hidden field inside the form:
#Html.Hidden("cid", "123")
or as a route value:
#using (Html.BeginForm(
"AjaxUpload",
"Cases",
new { cid = 123 },
FormMethod.Post,
new { enctype = "multipart/form-data", id = "ajaxUploadForm" }
))
{
...
}