I am using adobe creative sdk image editor and .net for my project. When I edit a image, only <"img"> is changing but I am sending <"input file">. I tried two way, firstly I send data to <"input file"> and later send to controller. But I didnt. Secondary directly <"img"> file to controller but again didnt work.`
Index
#using (Html.BeginForm("Save", "Tweet", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>TweetModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Content, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Content, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Content, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="col-md-10">
<input id="click-upload" name="file" type="file">
<div id="drop-area">
<p>Drop an image here!</p>
<p>(or click to upload)</p>
</div>
<img id="editable-image" onclick="read()" class="img-responsive">
</div>
</div>
<div class="col-md-12">
<button>Gönder</button>
</div>
}`
<script type="text/javascript">
function read()
{
var c = document.getElementById("editable-image");
document.getElementById("click-upload").innerHTML = c;
alert(document.getElementById("click-upload").size);
}
</script>
public ActionResult Save(Tweet tweetModel)
{
WebImage file = WebImage.GetImageFromRequest();
tweetModel.UserId = Convert.ToInt32(Session["UserId"]);
if (tweetModel.UserId > 0)
{
if (file.FileName !=null)
{
// code for saving the image file to a physical location.
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads/Image"), fileName);
file.Save(path);
// prepare a relative path to be stored in the database and used to display later on.
path = Url.Content(Path.Combine("~/Uploads/Image", fileName));
// save to db
tweetModel.Image = path;
}
CreateOrder(tweetModel);
}
return RedirectToAction("Index");
}
Related
I cannot figure out why my view only passes back a NULL for a model to my controller.
This is for an Edit Post method. I checked other controllers with Edit Post methods that are structured the same way as this one and they work fine. It seems to be just this view and controller.
Here is my view:
#model Non_P21_Quote_System_v1._0.Models.gl_code
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
#if (TempData["Message"] != null)
{
<div style="color:green">
#TempData["Message"]
</div><br />
}
#if (ViewBag.error != null)
{
<div style="color:red">
<h3>#ViewBag.error</h3>
</div><br />
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>gl_code</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.GL_code, "GL Code", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.GL_code, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.GL_code, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.GL_description, "Gl Description", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.GL_description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.GL_description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.expense_type_ID, "Expense", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("expense_type_ID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.expense_type_ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.eag, "Employee Account Group", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("eag", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.eag, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "gl_Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Here is my controller method:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "ID,GL_code,GL_description,expense_type_ID,eag")] gl_code gl_code)
{
if (ModelState.IsValid)
{
db.Entry(gl_code).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("gl_Index");
}
ViewBag.eag = new SelectList(db.employee_account_group, "ID", "eag_name");
ViewBag.expense_type_ID = new SelectList(db.expense_type, "ID", "type", gl_code.expense_type_ID);
return View(gl_code);
}
When I debug it, I see the model being passed in is of value NULL. I am seeing this on the controller side at the the parameters part of the Edit method.
Its null because your model contains a property named gl_code and you have also named the parameter for your model gl_code in the POST method.
Change the name of one or the other and the model will bind correctly.
What is happening internally is that the form submits a name/value pair for each successful form control, in your case gl_code=someValue. The DefaultModelBinder first initializes a new instance of your model. It then reads the form values and finds a match for the property in your model and sets it to someValue. But it also finds a match in the method parameters and tries set the value of the parameter to someValue, which fails (because you cannot do gl_code gl_code = "someValue";) and the model becomes null.
It appears you have a property on your view model called gl_code. In your controller, you also refer to the view model as gl_code.
Try changing this.
public async Task<ActionResult> Edit(gl_code gl_code)
To
public async Task<ActionResult> Edit(gl_code model)
Im trying to figure out how I can upload a profile image to my database within my asp.net mvc web project.
The issues is that im getting a Data URI instead of an actual file upload and that the URI is generated inside my javascript and im not sure how I can pass URI aswell as the other input fields inside my form to the controller.
View - Form
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.ProfilePicture, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<div id="wrapper" style="margin-top: 20px;">
<div class="image-editor">
<input type="file" class="cropit-image-input">
<div class="cropit-preview"></div>
<div class="image-size-label">
Resize image
</div>
<div class="controls-wrapper">
<div class="slider-wrapper">
<span class="icon icon-image small-image"></span>
<input type="range" class="cropit-image-zoom-input custom">
<span class="icon icon-image large-image"></span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.UserName, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Email, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.ConfirmPassword, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="hidden" name="profilePicture" class="hidden-image-data">
<input type="submit" class="btn btn-default" value="Register"/>
</div>
</div>
}
Javascript below the Form
<script src="~/Scripts/jquery.cropit.js"></script>
<script>
$(function() {
$('.image-editor').cropit({
imageBackground: true,
imageBackgroundBorderWidth: 20,
initialZoom: 'image',
smallImage: 'stretch',
imageState: {
src: '/Images/ProfilePictures/no-img.png'
}
});
$('form').submit(function () {
var imageData = $('.image-editor').cropit('export');
// imageData containing the Data URI for the cropped image
$('.hidden-image-data').val(imageData);
});
});
</script>
Controller - Register
public async Task<ActionResult> Register([Bind(Exclude = "ProfilePicture")]RegisterViewModel model) {
if (ModelState.IsValid) {
// To convert the user uploaded Photo as Byte Array before save to DB
byte[] imageData = null;
if (Request.Files.Count > 0) {
HttpPostedFileBase poImgFile = Request.Files["ProfilePicture"];
using (var binary = new BinaryReader(poImgFile.InputStream)) {
imageData = binary.ReadBytes(poImgFile.ContentLength);
}
}
.... more code ....
}
}
Feel free to ask for more explanatory details.
A data URI is a non-binary encoding of binary data. That is the data you want.
It's probably base64 encoded so you can just base64 decode it on the server side before you write it.
There's code here to encode into and from base64
Here's the example code from the site linked above:
public class Base64Decoder
{
public static void Main ()
{
string inputText = "This is some text.";
Console.Out.WriteLine ("Input text: {0}", inputText);
byte [] bytesToEncode = Encoding.UTF8.GetBytes (inputText);
string encodedText = Convert.ToBase64String (bytesToEncode);
Console.Out.WriteLine ("Encoded text: {0}", encodedText);
byte [] decodedBytes = Convert.FromBase64String (encodedText);
string decodedText = Encoding.UTF8.GetString (decodedBytes);
Console.Out.WriteLine ("Decoded text: {0}", decodedText);
Console.Out.Write ("Press enter to finish.");
Console.In.ReadLine ();
return;
}
}
I am trying to pass values to my controller, from my view using ajax. I am relatively new to using ajax so I need some help figuring this out.
Full Page
#model ALSummary.Models.MonthReport
#{
ViewBag.Title = "Index";
}
<h2><strong>Generate Monthly Report</strong></h2>
<br />
<hr />
#Html.BeginForm("Generate", "MonthReports", FormMethod.Post, htmlAttributes: new { id = "GenerateForm" }){
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Choose AC:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("AC", null, "-- Select AC --", htmlAttributes: new { id = "AC", #class = "form-control" })
</div>
</div>
</div>
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Choose Month:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Months", null, "-- Select Month --", htmlAttributes: new { id = "Month", #class = "form-control" })
</div>
</div>
</div>
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Year:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Years", null, "-- Select Year --", htmlAttributes: new { id = "Year", #class = "form-control" })
</div>
</div>
</div>
<br />
<input type="submit" id="SendToController" class="btn btn-primary" value="Generate" />
}
<script type="text/javascript">
$('#SendToController').on('click', function() {
sendToController();
return false;
});
function sendToController(){
var selectedAC = $('#AC').val();
var selectedMonth = $('#Month').val();
var chosenYear = $('#Year').val();
$.ajax({
url: #Url.Action("Generate", "MonthReports", null),
data: { 'id' : selectedAC, 'monthValue' : selectedMonth, 'year' : chosenYear },
type: 'GET',
cache: false,
success: function(data){},
});
}
</script>
Error Message:
Here is where the red squiggly lines are happenning when I receive the error message:
Your AJAX and Controller look fine... the error reported is because your javascript function can't be found (isn't present) at the time that the HTML is loaded for the Submit input (usually this is because the JS isn't loaded until after the DOM, my guess is that your script block is at the end of your body and not in the head (which is fine/preferred, just needs to be handled a bit differently)).
I typically prefer to bind events via JS rather than the HTML. Remove the onclick="sendToController()" from your HTML, and add this to your JavaScript:
$("#FormID").on('submit', function(event) {
event.preventDefault();
sendToController();
return false; // prevent submit from submitting
});
function sendToController() {
// your other code here
}
Change FormID to the ID of the form as required.
I have a form that contains another form.
the first form sends data to the action indicated in the beginform which the particular form it contains.
The second form ( contained in the first ) is a list that on change event, exchange a picture, this works .
but the first form is not sent yet.
how can I do to submit the first form normaly and the second with the javascript on change ?
#using (Html.BeginForm("VCreateCommande", "CCommande", new {id="formretouche"}, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
var imagedefaut = "";
#Html.AntiForgeryToken()
<h4>Retouchephoto</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group ilnblk">
<div class="control-label col-md-2 fltleft">Type de retouche</div>
<div class="col-md-10 fltleft">
#using (Html.BeginForm("VCreateCommande", "CCommande", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.DropDownListFor(model => model.Ttyperetouche.Idtyperetouche, new SelectList(
Model.Ttyperetouches, "Idtyperetouche", "libelle", ViewData["Idtyperetouche"]), new { #onchange = "this.form.submit()" })
} </div>
<div class="fltleft imagemodele">
#if (ViewData["Idtyperetouche"] != null)
{
foreach (var typeretouche in Model.Ttyperetouches)
{
if (typeretouche.Idtyperetouche.ToString() == ViewData["Idtyperetouche"].ToString())
{
imagedefaut = typeretouche.SRCtyperetouche;
}
}
}
else
{
imagedefaut = Model.Ttyperetouches.First().SRCtyperetouche;
}
<img src="#imagedefaut" />
</div>
</div>
<div class="form-group">
<div class="control-label col-md-2">Support papier</div>
<div class="col-md-10">
#Html.CheckBoxFor(model => model.Tretouche.Supportpapier, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Tretouche.Supportpapier, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="control-label col-md-2">Quantité</div>
<div class="col-md-10">
#Html.EditorFor(model => model.Tretouche.Quantite, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Tretouche.Quantite, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="control-label col-md-2">Photo...</div>
<div class="col-md-10">
#Html.TextBoxFor(model => model.Tretouche.fichierphoto, new { type = "file" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
#{
String onclick = String.Format("Submit(this)",
Html.Encode(ViewBag.returnUrl));
}
<input type="button" id="btnsubmitretouche" value="Ajouter1" onclick="#onclick" />
<input type="submit" value="Ajouter" class="btn btn-default"/>
</div>
</div>
}
It is not valid html5 to nest forms, see the W3C HTML5 Working Draft.
To submit form below I have to click <input type="submit" value="Save" /> which is at the bottom of form pasted below:
#model WebApplication2.Models.Person
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<input type="submit" value="Save" class="btn btn-success" style="width: 200px; font-weight: bold;" />
</div>
</div>
</div>
}
This causes invoking POST Edit method in PersonController:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,FirstName")] Person person) {
if (ModelState.IsValid) {
db.Entry(person).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(person);
}
I also would like to have a JavaScript function which does the same( when I invoke this function) but does not redirects me to any view. Just invokes POST Edit and passes contents of the form above.
Question: How to write JavaScript function which submits the form above without redirecting me anywhere?
function SubmitForm() {}
EDIT
I tried this.
The JavaScript method is invoked when I click #Html.ActionLink("Add a Report", "Create", "Reports", new { personId = Model.Id }, new { onclick = "SubmitForm()" }) (alert is displayed) but form is not submited(standard submit button works, so it is JavaScript function fault).
Form:
#using (Html.BeginForm(null, null, FormMethod.Post, new { name="myForm", id = "myForm" })) {
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<p> #Html.ActionLink("Add a Report", "Create", "Reports", new { personId = Model.Id }, new { onclick = "SubmitForm()" })</p>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<input type="submit" value="Save" class="btn btn-success" style="width: 200px; font-weight: bold;" />
</div>
</div>
</div>
}
and the function:
function SubmitForm() {
alert("IS INVOKED");
$("#myForm").submit();
}
Easiest way I have found. :
$("#myForm").submit();
Possible duplicate of. :
ASP.Net MVC, Submit a form using javascript
You also need to name your form. In this instance myFrom is the id of your form. Something like. :
Html.BeginForm(null, null, FormMethod.Get, new { name = "myForm", id = "myForm" })