ASP.Net MVC Ajax.BeginForm File Upload Response Issue - javascript

So I have a modal which allows a user to upload a file, I am wanting to get a json response back to say whether the upload was successful or not and display that to the end user.
Currently my View is this
#model int
<div id="modal_newSupportPlan" class="modal fade" style="display:none;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal">x</button>
<h6 class="modal-title">New Support Plan</h6>
</div>
#using (Ajax.BeginForm("CreateSupportPlan", "Client",
new AjaxOptions() { OnSuccess = "getSupportPlanResult", HttpMethod = "post" },
new { #Class = "form-horizontal", enctype = "multipart/form-data" }))
{
<div class="modal-body">
<input name="ClientFK" value="#Model" style="display:none" />
<div class="form-group" id="newsupportplan_error_plantype">
<label class="control-label col-sm-3">Type of Plan</label>
<div class="col-sm-9">
<select id="planType" name="PlanType" class="form-control">
<option></option>
<option value="1">Initial Plan</option>
<option value="2">Pre Employment Plan</option>
<option value="3">6 Month Plan</option>
<option value="4">12 Month Plan</option>
<option value="5">Ongoing Support Plan</option>
</select>
</div>
</div>
<div class="form-group" id="newsupportplan_error_StartDate">
<label class="control-label col-sm-3">Date</label>
<div class="col-sm-9">
<input type="text" class="form-control pickadate-accessibility" name="Date" />
</div>
</div>
<div class="form-group" id="newsuportplan_error_SLILevel">
<label class="control-label col-sm-3">Support Level</label>
<div class="col-sm-9">
<select id="SliLevel" name="SliLevel" class="form-control">
<option></option>
<option value="1">SLI 1</option>
<option value="2">SLI 2</option>
<option value="3">SLI 3</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">Upload File</label>
<div class="col-sm-9">
<input type="file" name="Blob" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
}
</div>
</div>
And my Controller method is this
[HttpPost]
public ActionResult CreateSupportPlan(ModelHelper.SupportPlanViewModel supportPlanDetails)
{
try
{
esp_storage_supportPlans espStorageSupportPlans = new esp_storage_supportPlans();
bool validation = true;
var errorList = new List<string>();
var passList = new List<string>();
if (string.IsNullOrEmpty(supportPlanDetails.PlanType.ToString()))
{
errorList.Add("SupportPlanType");
validation = false;
}
else
{
passList.Add("SupportPlanType");
}
if (string.IsNullOrEmpty(supportPlanDetails.Date.ToString()))
{
errorList.Add("Date");
validation = false;
}
else
{
passList.Add("Date");
}
if (string.IsNullOrEmpty(supportPlanDetails.SliLevel))
{
errorList.Add("SLILevel");
validation = false;
}
else
{
passList.Add("SLILevel");
}
if (supportPlanDetails.Blob != null && supportPlanDetails.Blob.ContentLength > 0)
{
if (validation)
{
var uploadedFile = new byte[supportPlanDetails.Blob.InputStream.Length];
supportPlanDetails.Blob.InputStream.Read(uploadedFile, 0, uploadedFile.Length);
espStorageSupportPlans.Blob = uploadedFile;
espStorageSupportPlans.ClientFK = supportPlanDetails.ClientFK;
espStorageSupportPlans.Date = Convert.ToDateTime(supportPlanDetails.Date);
espStorageSupportPlans.SliLevel = supportPlanDetails.SliLevel;
if (supportPlanDetails.PlanType == 1) espStorageSupportPlans.PlanType = "Initial Plan";
if (supportPlanDetails.PlanType == 2) espStorageSupportPlans.PlanType = "Pre Employment Plan";
if (supportPlanDetails.PlanType == 3) espStorageSupportPlans.PlanType = "6 Month Plan";
if (supportPlanDetails.PlanType == 4) espStorageSupportPlans.PlanType = "12 Month Plan";
if (supportPlanDetails.PlanType == 5) espStorageSupportPlans.PlanType = "Ongoing Support Plan";
string extension = Path.GetExtension(supportPlanDetails.Blob.FileName);
espStorageSupportPlans.Extn = extension;
espStorageSupportPlans.FileName = supportPlanDetails.Blob.FileName;
db.esp_storage_supportPlans.Add(espStorageSupportPlans);
db.SaveChanges();
}
}
else
{
errorList.Add("Blob");
validation = false;
}
if (!validation)
{
return Json(new { result = "Validation", errors = errorList, pass = passList }, JsonRequestBehavior.AllowGet);
}
return Json(new { result = "success" }, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(new { result = "failed" }, JsonRequestBehavior.AllowGet);
}
}
My javascript is the following 2 parts
first part has made the form work by uploading the file
window.addEventListener("submit", function (e) {
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
if (form.dataset.ajaxUpdate) {
var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
if (updateTarget) {
updateTarget.innerHTML = xhr.responseText;
}
}
}
};
xhr.send(new FormData(form));
}
}
}, true);
My second part is the onsuccess function but this is not being triggered. And stopped triggering when I implemented the first part to get the form uploading
function getSupportPlanResult(data) {
console.log("here");
if (data.result === "success") {
opts.title = "Completed";
type: "success";
opts.text = "Support Plan created successfully.";
opts.type = "success";
new PNotify(opts);
supportPlanTable.destroy();
BuildDataTable_SupportPlan();
$('#modal_newSupportPlan').modal('hide');
} else {
if (data.result === "validation") {
console.log(data);
} else {
opts.title = "Somthing Went Wrong";
opts.text = "Support Plan failed to create, please try again.";
opts.addclass = "stack-custom-bottom bg-danger";
opts.type = "error";
new PNotify(opts);
}
}
}

Why don't you use any library to do the dirty work of handling XHR for you? Like axios? The code could look then something like this:
window.addEventListener("submit", e => {
const form = e.target;
if (form.getAttribute("id") === '<my_unique_id_of_this_element>') {
axios({
method: form.method,
url: form.action,
data: /* whatever payload you need to send */
})
.then(({data}) => getSupportPlanResult(data));
}
});

Related

JavaScript code wont execute but get printed as part of html

I have this html code with js inside and every time i submit the js wont execute but get printed as html, saw many similar problems on stack overflow they said something about not closing <div> correctly but i cant find the error on my code
This is my html code:
<div class="container-fluid">
<div class="row" id="riparues_frm">
<form method="post" action="ruajRiparues.php" id="FormaRuaj_rp" enctype="multipart/form-data">
<input type="hidden" name="idRiparues" id="idRiparues" />
<div class="form-group row d-flex" style="margin-bottom: 20px;" >
<div class="col-sm-4">
<input type="button" class="btn btn-outline-info" value="Kerko skript sipas pershkrimit" onclick="lookUpBox({
title: 'Kerko skript sipas pershkrimit',
url: 'kerkoSkript_sipas_emrit.php?chars=',
onItemSelected: function(data){
$('input[id=' +
'idRiparues]').val(data.idRiparues);
$('#delref').attr('href','fshi_riparues.php?id=' + data.idRiparues);
$('input[name=kodi]').val(data.kodi);
$('input[name=seq]').val(data.sequenca);
$('input[name=pershkrimi]').val(data.pershkrimi);
$('#scripti').val(data.script);
$('#scripti').load(data.script, resizeArea);
$('#modelScripti').val(data.modelScript);
$('#modelScripti').load(data.modelScript, resizeArea);
$('#dataregj').val(data.datazgjedh);
$('#tipi').val(data.Tipi);
//kosta070622 start
var checkTipi = data.Tipi;
**filter()**
//kosta070622 end
},
tableHeader: ['idRiparues','kodi', 'pershkrimi','sequenca','script','modelScript','data']
})
" />&nbsp
</div>
and this is my js code:
<script>
function filter() {
if(isadmin === 1){
if(checkTipi != 'S' && checkTipi != 'B'){
document.getElementById('modelScripti').hidden = true;
document.getElementById('pathi').hidden = false;
document.getElementById('myfile').hidden = false;
document.getElementById('seq').disabled = true;
document.getElementById('lblpershkrimi').innerHTML = 'Emri Skedarit';
document.getElementById('lblscript').innerHTML = 'Pathi Relativ';
document.getElementById('lblmodelscript').innerHTML = 'Model Pathi Relativ';
$('#pathi').val(data.modelScript);
}else{
document.getElementById('modelScripti').hidden = false;
document.getElementById('pathi').hidden = true;
document.getElementById('myfile').hidden = true;
document.getElementById('seq').disabled = false;
document.getElementById('lblpershkrimi').innerHTML = 'Pershkrimi';
document.getElementById('lblscript').innerHTML = 'Script';
document.getElementById('lblmodelscript').innerHTML = 'Model Script';
}
}else{
if(checkTipi != 'S' && checkTipi != 'B'){
document.getElementById('modelScripti').hidden = true;
document.getElementById('pathi').hidden = false;
document.getElementById('myfile').hidden = true;
document.getElementById('seq').disabled = true;
document.getElementById('pathi').disabled = true;
document.getElementById('scripti').disabled = true;
document.getElementById('Edito').disabled = true;
document.getElementById('lblpershkrimi').innerHTML = 'Emri Skedarit';
document.getElementById('lblscript').innerHTML = 'Pathi Relativ';
document.getElementById('lblmodelscript').innerHTML = 'Model Pathi Relativ';
$('#pathi').val(data.modelScript);
}else{
document.getElementById('modelScripti').hidden = false;
document.getElementById('pathi').hidden = true;
document.getElementById('myfile').hidden = true;
document.getElementById('seq').disabled = false;
document.getElementById('scripti').disabled = false;
document.getElementById('Edito').disabled = false;
document.getElementById('lblpershkrimi').innerHTML = 'Pershkrimi';
document.getElementById('lblscript').innerHTML = 'Script';
document.getElementById('lblmodelscript').innerHTML = 'Model Script';
}
}
console.log(Boolean(isadmin));
console.log("HYRI KETU");
}
</script>
The html code it was written by someone else i just added the function filter and thats the the code that is being printed as html on the website.
I think that you are missing 3 div closing tags, and that is why your script is being read as html.
//1<div class="container-fluid">
//2<div class="row" id="riparues_frm">
<form method="post" action="ruajRiparues.php" id="FormaRuaj_rp" enctype="multipart/form-data">
<input type="hidden" name="idRiparues" id="idRiparues" />
//3 <div class="form-group row d-flex" style="margin-bottom: 20px;" >
//4 <div class="col-sm-4">
<input type="button" class="btn btn-outline-info" value="Kerko skript sipas pershkrimit" onclick="lookUpBox({
title: 'Kerko skript sipas pershkrimit',
url: 'kerkoSkript_sipas_emrit.php?chars=',
onItemSelected: function(data){
$('input[id=' +
'idRiparues]').val(data.idRiparues);
$('#delref').attr('href','fshi_riparues.php?id=' + data.idRiparues);
$('input[name=kodi]').val(data.kodi);
$('input[name=seq]').val(data.sequenca);
$('input[name=pershkrimi]').val(data.pershkrimi);
$('#scripti').val(data.script);
$('#scripti').load(data.script, resizeArea);
$('#modelScripti').val(data.modelScript);
$('#modelScripti').load(data.modelScript, resizeArea);
$('#dataregj').val(data.datazgjedh);
$('#tipi').val(data.Tipi);
//kosta070622 start
var checkTipi = data.Tipi;
filter()
//kosta070622 end
},
tableHeader: ['idRiparues','kodi', 'pershkrimi','sequenca','script','modelScript','data']
})
" />&nbsp
//1 </div>
//2 </div> //this and below are added by me
//3</form>
//4 </div>
//5 </div>

why javascript-ajax submitting form multiple times

I am doing single page app. If i type something on form and click the submit button then it sends one request. Second time if i type something and click it sends two requests. Third time it sends three requests and so on. Why is this? Did i do any mistake in javascript code?
here is my html
function reply_mail(idi) {
document.querySelector('#emails-view').style.display = 'none';
document.querySelector('#compose-view').style.display = 'none';
document.querySelector('#reply-view').style.display = 'block';
fetch(`/emails/${idi}`)
.then(response => response.json())
.then(email => {
// Print email
var strp = `${email.subject}`;
var ini = 'Re: '
document.querySelector('#reply-recipients').value = `${email.sender}`;
if (strp.slice(0, 4) == 'Re: ') {
document.querySelector('#reply-subject').value = `${strp}`;
} else {
document.querySelector('#reply-subject').value = ini.concat("", strp);
}
var output = `On ${email.timestamp} ${email.sender} wrote:|
${email.body} |
`;
// ... do something else with email ...
document.querySelector('#reply-body').value = output;
// ... do something else with email ...
console.log(email);
});
document.querySelector('#reply-submit').addEventListener('click', function(event) {
event.preventDefault();
rec = document.querySelector('#reply-recipients').value;
sub = document.querySelector('#reply-subject').value;
bod = document.querySelector('#reply-body').value;
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: rec,
subject: sub,
body: bod
})
})
.then(response => response.json())
.then(result => {
// Print result
if ('error' in result) {
console.log(result);
document.querySelector('#reply-error').style.display = 'block';
document.querySelector('#reply-error-i').innerHTML = `<p>${result['error']}</p>`;
} else {
console.log(result);
document.querySelector('#reply-error').style.display = 'none';
load_mailbox('sent');
}
});
})
}
```
<div id="reply-view">
<h3>New Email</h3>
<div class="alert alert-danger" role="alert" id="reply-error">
<div id="reply-error-i">
</div>
</div>
<form id="reply-form">
<div class="form-group">
From: <input disabled class="form-control" value="soham#example.com">
</div>
<div class="form-group">
To: <input id="reply-recipients" class="form-control">
</div>
<div class="form-group">
<input class="form-control" id="reply-subject" placeholder="Subject">
</div>
<textarea class="form-control" id="reply-body" placeholder="Body"></textarea>
<input type="submit" id="reply-submit" class="btn btn-primary" />
</form>
</div>

Autofill textbox based on dropdown list selection which is binded from db in asp.net mvc

This is view part:
In this view part Product name dropdown is retrieved from database , what iam trying to do is after selecting product name, price must be populated in the price textbox. Product name, price and other columns are already stored in db.
<div class="form-group">
<div class="row">
<label class="col-sm-8 control-label no-padding-right">Product Name</label>
</div>
<div class="row">
<div class="col-sm-8">
#Html.DropDownList("Product_Name", (SelectList)ViewBag.Values, "Please select", new { #id = "populate", #class = "SelectCtrlGHN", onchange = "return get_sbu(this)" })
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<label class="col-sm-8 control-label no-padding-right">Price</label>
</div>
<div class="row">
<div class="col-sm-8">
<input type="text" name="Price" class="col-xl-4 col-sm-8" id="pric" />
</div>
</div>
</div>
Script to retrieve price :
Here i have written script to retrieve price according to the corresponding dropdown list selection in view.
<script type="text/javascript">
$(document).ready(function() {
$('#populate').change(function() {
var str = this.options[this.selectedIndex].value;
var st = null;
$.ajax('#Url.Action("GetProductData", "Userrolereq")', {
type: 'POST',
dataType: 'json',
data: { 'productID': str },{'amt':st},
success: function(data, status, jqXHR) {
if ("success" === status) {
document.getElementById('#populate').value = data.productID;
document.getElementById('#pric').value = data.amt;
}
if ("productCode" != null) {
document.getElementById('#pric').value = data.amt;
}else {
alert('This Product ID is not valid. Try again!');
}
}
});
});
});
</script>
This is Controller:
From DM_Userreq table in database iam trying to retrieve price from dropdown selection.
public ActionResult GetProductData(string productID)
{
string sa = "";
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
StringBuilder sb = new StringBuilder();
using (cn)
{
cn.Open();
string que = string.Format("Select Price From DM_Userreq Where Product_Name = '{0}'", productID);
SqlCommand cm = new SqlCommand(que, cn);
SqlDataReader rd = cm.ExecuteReader();
while (rd.Read())
{
sb.Append(rd["Price"].ToString() + "</br>");
return Json(new { success = true, productCode = sb.Append(rd["Price"].ToString() + "</br>") });
}
sa = sb.ToString();
cn.Close();
}
return Json(new { success = false });
}

Delete required on input before submitted in ajax

I tried to validate by submitting a form by using ajax on codeigniter, when I want to insert data but only a few input fields only and input field that I do not use I try to hide, but attr required still running on the input field that I have hidden, how to solve this. so delete the required input field when hidden.
Views
<form id="fr" method="post" class="form-horizontal form-label-left">
<div class="form-group">
<label for="fullname">Section * :</label>
<select name="section" class="form-control" required="required">
<option value="">Select section</option>
<option value="manager">Manager</option>
<option value="head manager">Head Manager</option>
</select>
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="nama">Kitchen * :</label>
<input type="text" name="name_kitchen" class="form-control" required="required" />
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="nama">Resto * :</label>
<input type="text" name="name_resto" class="form-control" required="required" />
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="fullname"> </label><br>
<button type="button" id="submit" class="btn btn-primary"><i class="fa fa-save"></i> Simpan</button>
</div>
</form>
<script>
$("[name='section']").change(function(){
var value=$(this).val();
if(value == "manager"){
$("[name='name_kitchen']").hide();
$("[name='name_resto']").show();
}else{
$("[name='name_kitchen']").show();
$("[name='name_resto']").hide();
}
});
$("#submit").click(function() {
$.ajax({
type: "POST",
url: base_url+"add",
dataType: 'json',
data: $('#fr').serialize(),
success: function(data) {
if(data.status) {
$(".add-from-staff").toggle("slow");
$("#fr").load(location.href + " #fr");
$('form#fr input[type="text"],texatrea, select').val('');
}else {
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error');
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]);
}
}
},
error: function (request, jqXHR, textStatus, errorThrown) {
alert('Error');
console.log(request.responseText);
}
});
});
</script>
Controllers
public function add() {
$this->_validate();
$insert = $this->My_models->_add();
echo json_encode(array("status" => TRUE));
}
function _validate() {
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('name_kitchen') == '')
{
$data['inputerror'][] = 'name_kitchen';
$data['error_string'][] = 'Kitchen is required';
$data['status'] = FALSE;
}
if($this->input->post('name_resto') == '')
{
$data['inputerror'][] = 'name_resto';
$data['error_string'][] = 'Resto is required';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
so how when I choose one of the select options that hide disabled required?
when u are hiding any div u can get the element and remove its required attribute using jquery
$("[name='name_kitchen']").removeAttr('required');
e.g:
$("#elementID").removeAttr('required');
In this example I would not use the required attribute. It is causing more headaches than it is worth. Instead, rely on the server-side validation.
To determine which "section" is in use it seems to me that passing another piece of info to the controller would be the easiest way to solve the problem. This could be done many different ways. Adding another hidden field is one option.
Somewhere inside the <form> add
<input type="hidden" id="use-section" name="use_section" value="">
It is not clear that you have a "default" section shown when you first show the page. If there is one then use that for the "value" in the above field.
During the handler
$("[name='section']").change(function(){ ...
set the value of the "use_section" field.
var value=$(this).val();
$("#use-section").val(value);
You can evaluate the "use_section" in your controller, or in your case, in the model which is where I assume you are capturing the data posted.
if($this->input->post('use_section') === "manager")
{
//get the fields you want
}
else
{
//get the other fields
}
I have a suggestion regarding _validate(). Instead of calling exit() to short-circuit add() return a value - TRUE if it works, or $data if it doesn't. The last few lines of _validate() become
if($data['status'] === FALSE)
{
return $data;
}
return TRUE;
Then use this add() method
public function add()
{
if(TRUE === ($status = $this->_validate()))
{
$insert = $this->My_models->_add();
$status = array("status" => TRUE);
}
echo json_encode($status);
}
Use of exit or die in CodeIgniter is, IMO, not appropriate because it short-circuits the framework's designed execution flow.

ng-disabled nor enabling Submit button

I hope you can help me.
I think I am missing something, and just can't figure it out. For some reason I cannot get ng-disabled="formSubmmision" to enable the button when the form has been filled in.
Any help will be greatly appreciated!
I have the following view and controller:
Here is my view:
<section class="mainbar" data-ng-controller="adminVendorNumberController as vm">
<article class="booty">
<div class="row-fluid">
<div class="col-md-12">
<h1 class="main-heading"><strong>Vendor Number Admin</strong></h1>
</div>
</div>
<form name="formInsertVendorNumber" novalidate>
<div class="row-fluid island">
<div class="col-md-12">
<div>
<!--Here-->
<div class="header">
<div class="green"><span class="icon-user-tie"></span></div>
<h2 class="title">Add New <strong>Vendor Number</strong></h2>
</div>
<div class="row-fluid">
<!-- Customer-->
<div class="col-md-4">
<label>Vendor</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="Select Vendor"
ng-model="NewVendorNumber.Vendor"
ng-disabled="false"
ng-options="vendorData"
cc-fields="VendorDescription"
cc-key-field="VendorId"
cc-allow-search="false"
ng-required="false"
ng-change="vendorSelected()"
name="iVendor">
</cc-dropdown>
</div>
</div>
<!-- End Customer-->
<!--Region -->
<!-- Update: ng-disabled="NewVendorNumber.Vendor == null" -->
<div class="col-md-4">
<label>Item Group</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="Select Item Group"
ng-model="NewVendorNumber.ItemGroup"
ng-disabled="NewVendorNumber.Vendor == null"
ng-options="itemGroupData"
cc-fields="ItemGroupDescription"
cc-key-field="ItemGroupId"
cc-allow-search="false"
ng-required="false"
ng-change="itemGroupSelected()"
name="iItemGroup">
</cc-dropdown>
</div>
</div>
<!--End Region -->
<div class="col-md-4">
<label>Vendor Item Number</label>
<div class="input-text">
<input type="text" name="iVendorItemNumber" required ng-model="NewVendorNumber.ItemNumber" />
<div class="errorIcon fadeInOut" ng-class="{error : VendorItemError}" ng-mouseenter="VendorItemError = true" ng-mouseleave="VendorItemError = false"
ng-show="(formInsertVendorNumber.$submitted || formInsertVendorNumber.iVendorItemNumber.$touched) && formInsertVendorNumber.iVendorItemNumber.$error.required">
<span class="icon-warning"></span>
<div>
<p>
<span>Please enter a Vendor Item Number</span>
</p>
</div>
</div>
</div>
</div>
<div class="col-md-8">
<label>Vendor Item Description</label>
<div class="input-text">
<input type="text" name="iVendorItemDescription" required ng-model="NewVendorNumber.ItemDescription" />
<div class="errorIcon fadeInOut" ng-class="{error : VendorItemDescriptionError}" ng-mouseenter="VendorItemDescriptionError = true" ng-mouseleave="VendorItemDescriptionError = false"
ng-show="(formInsertVendorNumber.$submitted || formInsertVendorNumber.iVendorItemDescription.$touched) && formInsertVendorNumber.iVendorItemDescription.$error.required">
<span class="icon-warning"></span>
<div>
<p>
<span>Please enter a Vendor Item Description</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="separator"></div>
<div class="footer">
<!-- Update: ng-disabled="formSubmmision" -->
<button type="submit" class="btn btn-default right" ng-click="save()" ng-disabled="formSubmmision"><span class="icon-checkmark"> </span>Save</button>
</div>
</div>
</div>
</div>
</form>
</article>
</section>
Here is my controller:
(function () {
"use strict";
angular
.module('app.adminVendorNumber')
.controller('adminVendorNumberController', adminVendorNumberController);
adminVendorNumberController.$inject = ['$http', 'logger', '$scope'];
function adminVendorNumberController($http, logger, $scope) {
var vm = $scope;
vm.formSubmmision = true;
vm.vendorItemData = null;
vm.itemGroupData = null;
vm.vendorData = null;
vm.vendorSelected = vendorSelected;
vm.itemGroupSelected = itemGroupSelected;
vm.save = save;
activate();
function activate() {
return vendorItemData().then(getAllItemGroups).then(getVendorData).then(function () {
logger.info('Activated Vendor Number Creation');
});
}
function vendorItemData(data) {
return $http.get('/api/vendorItem/getAll/')
.then(Success)
.catch(Failure);
function Success(responce) {
vm.vendorItemData = responce.data.Records;
return vm.vendorItemData;
}
function Failure(error) {
logger.error('Failed to Get Customer Data ' + error.data.Message);
}
}
function getVendorData(data) {
return $http.get('/api/vendor/GetAllVendors/')
.then(Success)
.catch(Failure);
function Success(responce) {
vm.vendorData = responce.data.Records;
return vm.vendorData;
}
function Failure(error) {
logger.error('Failed to Get Vendor Data ' + error.data.Message);
}
}
function getAllItemGroups(data) {
return $http.get('/api/itemGroup/GetAllItemGroups/')
.then(Success)
.catch(Failure);
function Success(response) {
vm.itemGroupData = response.data.Records;
return vm.itemGroupData;
}
function Failure(error) {
logger.error('Failed to Get Item Group Data ' + error.data.Message);
}
}
// Form Selections
function itemGroupSelected() {
vm.formSubmmision = true;
return getItemGroupById(vm.NewVendorNumber.ItemGroup.ItemGroupId);
}
function getItemGroupById(itemGroupId) {
return $http.get("/api/itemGroup/GetItemGroupById/?itemGroupId=" + itemGroupId)
.then(Success)
.catch(Failure);
function Success(responce) {
vm.itemGroupSelected = responce.data.Records;
return vm.itemGroupSelected, responce.data;
}
function Failure(error) {
logger.error('Failed to get Vendor Data ' + error.data.Message);
}
}
function vendorSelected() {
vm.formSubmmision = true;
return getVendorById(vm.NewVendorNumber.Vendor.VendorId);
}
function getVendorById(vendorId) {
return $http.get("/api/vendor/ReadVendor/?vendorid=" + vendorId)
.then(Success)
.catch(Failure);
function Success(responce) {
vm.vendorSelected = responce.data.Records;
return vm.vendorSelected, responce.data;
}
function Failure(error) {
logger.error('Failed to get Vendor Data ' + error.data.Message);
}
}
// Save
function save() {
if (vm.formInsertVendorNumber.$valid) {
postNewData();
}
else {
logger.error('Error: Validation failed. Please correct data and try again');
vm.formSubmmision = false;
}
}
function postNewData() {
//prepare data
var data = {
VendorItemId: 0,
ItemNumber: vm.NewVendorNumber.ItemNumber,
ItemDescription: vm.NewVendorNumber.ItemDescription,
ItemType: "",
OnCall: "",
Vendor: {
VendorId: vm.NewVendorNumber.Vendor.VendorId,
VendorDescription: vm.NewVendorNumber.Vendor.VendorDescription,
Active: vm.NewVendorNumber.Vendor.Active,
Id: vm.NewVendorNumber.Vendor.Id,
ChangedDate: vm.NewVendorNumber.Vendor.ChangedDate
},
ItemGroup: {
ItemGroupId: vm.NewVendorNumber.ItemGroup.ItemGroupId,
ItemGroupDescription: vm.NewVendorNumber.ItemGroup.ItemGroupDescription,
Id: vm.NewVendorNumber.ItemGroup.Id,
ItemCodeGroup: vm.NewVendorNumber.ItemGroup.ItemCodeGroup
}
}
$http.post('/api/vendorItem/PostVendorItem/', data)
.then(postDataComplete)
.catch(getDataFailed);
function postDataComplete(response) {
logger.info("Vendor Item Number Created ");
vm.NewVendorNumber = null;
vm.formSubmmision = true;
vm.formInsertVendorNumber.$setPristine();
vm.formInsertVendorNumber.$setUntouched();
return vm.NewVendorNumber;
}
function getDataFailed(error) {
logger.error('Failed to Vendor Item Number ' + error.data.Message);
return;
}
}
};
}
)();
you are using CONTROLLER AS syntax.
Your controller should be ...
var vm = this;
NOT ...
var vm = $scope;
also you should be using ...
formInsertVendorNumber.$valid to disable or enable the submit button.
you should, inside your form, display ...
<span>{{ formInsertVendorNumber }}</span>
This will output a lot of angular variables associated with the form. You should see that formInsertVendorNumber.$valid is true when the form is valid and false when it is not. use that to toggle your button.
I solved my problem by adding another simple function called formSubmit() to my controller:
function getItemGroupById(itemGroupId) {
return $http.get("/api/itemGroup/GetItemGroupById/?itemGroupId=" + itemGroupId)
.then(Success)
.then(formSubmit)
.catch(Failure);
function Success(responce) {
vm.itemGroupSelected = responce.data.Records;
return vm.itemGroupSelected, responce.data;
}
function Failure(error) {
logger.error('Failed to get Vendor Data ' + error.data.Message);
}
}
function formSubmit() {
vm.formSubmmision = false;
return vm.formSubmmision;
}

Categories

Resources