how to use WebImage.GetImageFromRequest and JQuery and MVC - javascript

Has anyone has an example using WebImage.GetImageFromRequest(); and Jquery to retrieve the file content?
I have this form and works fine without using Jquery. But after implementing Jquery I cannot retrieve data out of my object nor can get the file that I retrieved using WebImage.GetImageFromRequest helper.
I have seen a lot of examples utilising Jquery retriving just files, but not an example where I can retrieve data's object AND the file helper (WebImage.GetImageFromRequest();)
Html
<form action="" class="form-validate form-horizontal" id="form" method="POST" enctype = "multipart/form-data">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="form-group">
#Html.LabelFor(model => model.ImagenArchivoFoto, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="row">
<div class="col-md-6">#Html.TextBoxFor(model => model.GetFile, new { #class = "form-control", #id = "txtUbic2", #readonly = "readonly" })</div>
<div class="col-md-2"><input type="button" class="btn btn-default" value="..." id="btnUbic2" /></div>
<input type="file" name="ImagenArchivoFoto" id="GetFile" value="" style="display:block;height:0;width:0;" />
</div>
</div>
Jquery
var user= new Object();
user.Name= $("#Name").val();
user.LastName= $("#LastName").val();
$.ajax({
type: 'POST',
method: 'POST',
url: '/Users/Create/',
cache: false,
contentType: false,
processData: false,
dataType: 'json',
data: user,
success: function (data) {
if (data.ErrorStatus == 0) {
$.notify({
message: data.NotifyMessage
}, {
type: "success",
delay: 5000,
animate: {
enter: 'animated fadeInDown',
exit: 'animated fadeOutUp'
}
});
.net
[HttpPost]
public async Task<JsonResult> Create(CreateUsuarerViewModel user)
{
user.GetFile= WebImage.GetImageFromRequest();
}

Related

Binding jquery post data to c# type [duplicate]

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)

Call JS method from Razor form submit

When I submit the form I want to fire-up the Javascript method written below. This JS method will send a POST request to the backend. However, in the code written below this JS method is not being fired. Can someone please help me how to correct this ?
#using (Html.BeginForm(null, null, FormMethod.Post, new { #class = "form-horizontal", onsubmit = "submitdata" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<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 {id ="Email", #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.pwd, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.pwd, new {id="pwd", #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="submit" class="btn btn-default" value="Register" onsubmit="submitdata"/>
</div>
</div>
}
Javascript
function submitdata() {
var pwd = document.getElementById("pwd");
var email = document.getElementById("email");
$.ajax({
type: 'post',
url: '/Account/Reg',
data: {
email: email,
password: pwd
},
success: function (response) {
$('#success__para').html("You data will be saved");
}
});
return false;
}
You miss () in your onsubmit attribute;
onsubmit = "submitdata()"
As Vostrugin mentioned in his answer, you are missing () in the method call.
Here is the unobtrusive javascript way (using jQuery)
function submitdata() {
// your existing code
}
$(function(){
$("form").submit(function(e){
e.preventDefault();
submitData();
});
});
If you want to wire it with a specific button click, use a jQuery selector to get the button and bind the click event.
<input type="submit" id="myButton" value="Register"/>
and
$(function(){
$("#myButton").click(function(e){
e.preventDefault();
submitData();
});
});
With this approach, you should remove the onsubmit event from your UI markup.

Ajax Values to Controller Method

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.

how to add Razor element dynamically with new name and id?

I have following razor code. I need to add this dynamically on button click in client side.
<div class="form-group" id="transitem" name="transitem">
<div class="col-md-11" id="tritem" name="tritem">
#Html.LabelFor(model => model.transaction_item_id, "transaction_item_id", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-3">
<div id="trans_dd_1" name="trans_dd_1">#Html.DropDownList("transaction_item_id", null, htmlAttributes: new { #class = "form-control", #id = "trans_id_#", #Name = "trans_id_#" })</div>
#Html.ValidationMessageFor(model => model.transaction_item_id, "", new { #class = "text-danger" })
</div>
<div>
#Html.LabelFor(model => model.transaction_itmQty, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-3">
#Html.EditorFor(model => model.transaction_itmQty, new { htmlAttributes = new { #class = "form-control", #id = "trans_qty_#", #Name = "trans_qty_#" } })
#Html.ValidationMessageFor(model => model.transaction_itmQty, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-2"><input type="button" class="btnPlus" value="+" /></div>
</div>
</div>
I have written following script, but it is not working as expected. I need to change the name and id of trans_id_# and trans_qty_#. They are being generated by html helper, html.editorfor. Below is my script, which can copy the new element, but i am not able to change the id or name.
<script type="text/javascript">
var itm_cnt = 1;
$(document).ready(function () {
$(document).on("click", ".btnPlus", function () {
var new_clone = $('#tritem').clone();
itm_cnt = itm_cnt + 1;
var new_name = "trans_id_" + itm_cnt.toString();
$(new_clone).attr("name", "new_name");
$('#transitem').append(new_clone);
window.alert(itm_cnt);
});
});

Moving the submit button outside the form in MVC 5 with Partial view

In MVC 5,
I have a Dialog for editing.
The Content area is created from a Partial view.
If I have the submit button inside the form in the Partial view it works. But I would like the Save button to be at the button of the Dialog and hence outside the form and Partial view.
The problem is now that the forms data doesn't get posted. How would you fix this?
I have two ideas:
1) Wrap the form outside the Partial view
2) Make a AJAX request and not use the helper, and collect the data from the form somehow? Doesn't feel like the right way.
Dialog:
<div id="myModal" class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Edit database connection</h4>
</div>
<div class="modal-body">
#{ Html.RenderPartial("View"); }
</div>
<div class="modal-footer">
<button id="saveBtnSettings" type="button" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Dialog javascript
var saveSettings = function () {
var url = buildUrl("Edit", "Setting");
$.ajax({
type: "POST",
url: url
})
.done(function (data, textStatus, jqXhr) {
alert('done' + data);
})
.fail(function (jqXhr, textStatus, errorThrown) {
alert(textStatus.toUpperCase() + ": " + errorThrown + 'Could not load html. ');
});
};
Partial view
#using (Ajax.BeginForm("Edit", "Setting", new AjaxOptions { UpdateTargetId = "div" }))
{
<fieldset>
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.User, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.User, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.User, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DataSource, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DataSource, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DataSource, "", new { #class = "text-danger" })
</div>
</div>
</div>
</fieldset>
}
Partial view - Works with button inside of the form
#using (Ajax.BeginForm("Edit", "Setting", new AjaxOptions { UpdateTargetId = "div" }))
{
<fieldset>
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.User, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.User, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.User, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DataSource, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DataSource, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DataSource, "", new { #class = "text-danger" })
</div>
</div>
<p>
<input type="submit" value="Calculate" /> #* WORKS WITH BUTTON INSIDE OF FORM *#
</p>
</div>
</fieldset>
}
You can place a submit button outside the form tags by specifying the form attribute (HTML5 only)
<form .... id="editform">
....
</form>
<input type="submit" form="editform" />
Note if the submit button has a value attribute, it won't be posted back.
Another option may be to use css to position it.
Just submit the form using Javascript:
function SubmitMyForm(){
document.getElementById("myForm").submit();
}
HTML:
<input type="button" value="Calculate" onclick="SubmitMyForm()" />
I think you're looking for: document.myform.submit();
Here is a Fiddle adapted form of code from this page.

Categories