ASP.NET MVC AJAX POST 500 Internenal Server Error - asp.net

I want to update the row but when I click the update buttton return json result that message "500 Internenal Server Error". I don't find the problem. Can you check the code?
[HttpPost]
public JsonResult UpdateInStock(int stokID, int amount, int uCost, int sumCost, string detail, string unit)
{
var model = db.tbl_InStock.Where(x => x.stockInID == stokID).FirstOrDefault();
model.stockInAmount = amount;
model.stockInCost = uCost;
model.stockInSum = sumCost;
model.stockInDetail = detail;
model.stockInUnit = unit;
//db.SaveChanges();
return Json(new { result = "Redirect", url = Url.Action("Gelen", "Anasayfa") });
}
I want to update the row but when I click the update buttton return json result that message "500 Internenal Server Error". I don't find the problem. Can you check the code?
//Jquery Code
$("#uptInStock").click(function () {
var no = $.trim($("#stokInIDD").val());
var miktar = $.trim($("#amountt").val());
var fiyat = $.trim($("#unitCostt").val());
var toplam = $.trim($("#sumCostt").val());
var detay = $.trim($("#detaill").val());
var birim = $.trim($("#birimm option:selected").text());
var obj = { stokID: no, amount: miktar, uCost: fiyat, sumCost: toplam, detail: detay, unit: birim };
$.ajax({
type: "POST",
url: 'UpdateInStock',
crossDomain: true,
data: JSON.stringify(obj),
contentType: 'application/json;charset=utf-8"',
dataType: 'json',
success: function (response) {
if (response.result == 'Redirect')
window.location = response.url;
alert("Suc");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
//Html Code
#using (Html.BeginForm("UpdateInStock", "Anasayfa", FormMethod.Post))
{
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Gelen Ürün - Güncelle</h5>
</div>
<div class="modal-body">
<input type="hidden" class="form-control" id="proIDD" />
<input type="hidden" class="form-control" id="stokInIDD" />
<div class="form-group">
<label class="sr-only mb-4" for="inlineFormInputGroup">Miktar</label>
<div class="proUnit2 input-group mb-4">
<div class="input-group-prepend">
<div class="input-group-text">Miktar</div>
</div>
<input type="text" class="form-control" id="amountt" />
</div>
</div>
<div class="form-group">
<select class="form-control mb-4" id="birimm" name="birim">
<option value="0">Birim Seçiniz</option>
<option value="1">Adet</option>
<option value="2">Bidon</option>
<option value="3">Koli</option>
<option value="4">Paket</option>
</select>
</div>
<div class="form-group">
<label class="sr-only mb-4" for="inlineFormInputGroup">Birim Fiyatı</label>
<div class="proUnit input-group mb-4">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fa fa-try" aria-hidden="true"></i></div>
</div>
<input type="text" class="form-control" id="unitCostt" placeholder="Birim fiyatı" />
</div>
</div>
<div class="form-group">
<label class="sr-only mb-4" for="inlineFormInputGroup">Toplam Fiyatı</label>
<div class="proUnit input-group mb-4">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fa fa-try" aria-hidden="true"></i></div>
</div>
<input type="text" class="form-control" id="sumCostt" placeholder="Toplam fiyatı" />
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" id="detaill" placeholder="Açıklama" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Vazgeç</button>
<button id="uptInStock" type="button" class="btn btn-primary btn-sm">Kaydet</button>
</div>
}

Please try your url with Controller,ActionAnd Area if necessary. Below is some sample url you can try.
url:"/Area/Controller/ActionName" (in your case UpdateInStock is your action name)
url:"/Controller/ActionName"
Or you can use #Url.Action with razor syntax.
url:"#Url.Action("ActionName", "Controller")"

I solved the problem. The problem was with the numbers with commas.
var fiyat = $.trim($("#unitCostt").val());
var toplam = $.trim($("#sumCostt").val());
These fields should be converted to float values.
var fiyat = parseFloat($.trim($("#unitCostt").val()));
var toplam = parseFloat($.trim($("#sumCostt").val()));

Related

ASP.NET Double validation, custom message for numbers only

I have a validation for Fueling property which is a double.
[Display(Name = "Tankolás")]
[DisplayFormat(DataFormatString = "{0} l", ApplyFormatInEditMode = false)]
public double? Fueling { get; set; }
If I type letters instead of number in the input I get the error message: The value 'test' is not valid for Tankolás.
How could I change the error message?
Here is the view:
<div class="form-group">
<label asp-for="Fueling" class="control-label"></label>
<input id="Fueling" asp-for="Fueling" class="form-control" placeholder="Tankolás" />
<span asp-validation-for="Fueling" class="text-danger"></span>
</div>
EDIT - Full View code
#model MainProject.Models.RoadRecord
#{
ViewData["Title"] = "Hozzáadás";
}
<head>
<link rel="stylesheet" href="~/css/RoadRecords/create.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<div class="container">
<div class="text-center">
<h2>Új Menetlevél hozzáadása</h2>
</div>
<div class="row justify-content-center">
<div class="col-8">
<form asp-action="Create">
<input type="hidden" asp-for="UserId" />
<input type="hidden" asp-for="LicencePlate" />
<div class="form-group">
<label asp-for="Mileage" class="control-label"></label>
<div class="input-group-sm">
<input asp-for="Mileage" class="form-control" placeholder="Kilométer" />
<div id="mileageContainer" class="input-group-append">
<partial name="_ShowMileagePartialView.cshtml" model="#Model" />
</div>
</div>
<span asp-validation-for="Mileage" class="text-danger"></span>
#if (!string.IsNullOrEmpty(ViewBag.Message))
{
<span class="text-danger">
#ViewBag.Message
</span>
}
</div>
#*
<div class="form-group">
<label asp-for="TimeStamp" class="control-label"></label>
<input type="datetime-local" asp-for="TimeStamp" class="form-control" value="#DateTime.Now.ToString("yyyy-MM-ddTHH:mm")" />
<span asp-validation-for="TimeStamp" class="text-danger"></span>
</div>
*#
<div class="form-group">
<label asp-for="Location" class="control-label"></label>
<div class="input-group">
<input id="varos" type="text" asp-for="Location" class="form-control" aria-describedby="getLocationButton" />
<div class="input-group-append">
<button type="button" class="btn btn-primary" id="getLocationButton">Pozícióm</button>
</div>
</div>
<span asp-validation-for="Location" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Type" class="control-label"></label>
<select id="selectType" asp-for="Type" class="form-control">
<option selected value="C">Céges</option>
<option value="M">Magán</option>
</select>
</div>
<div class="form-group">
<label asp-for="Fueling" class="control-label"></label>
<input id="Fueling" asp-for="Fueling" class="form-control" placeholder="Tankolás" />
<span asp-validation-for="Fueling" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Note" class="control-label"></label>
<input asp-for="Note" class="form-control" placeholder="Megjegyzés" />
<span asp-validation-for="Note" class="text-danger"></span>
</div>
<div class="form-group">
#Html.AntiForgeryToken()<input onclick="ConvertDouble()" type="submit" value="Hozzáadás" class="btn btn-primary w-100" />
</div>
</form>
<a class="add" asp-action="Index" asp-route-licencePlate="#ViewBag.LicencePlate">
<button type="button" class="btn btn-secondary w-100">
Vissza
</button>
</a>
</div>
</div>
</div>
#section Scripts {
<!--GEO Location-->
<script>
$(document).ready(function () {
$('#getLocationButton').click(function () {
$.getJSON('https://geolocation-db.com/json/')
.done(function (location) {
$('#country').html(location.country_name);
$('#state').html(location.state);
$('#city').html(location.city);
$('#latitude').html(location.latitude);
$('#longitude').html(location.longitude);
$('#ip').html(location.IPv4);
document.getElementById('varos').value = location.city;
});
});
});
$.getJSON('https://geolocation-db.com/json/')
.done(function (location) {
console.log("kint");
if (document.getElementById('varos').value == '') {
console.log("bent");
$('#country').html(location.country_name);
$('#state').html(location.state);
$('#city').html(location.city);
$('#latitude').html(location.latitude);
$('#longitude').html(location.longitude);
$('#ip').html(location.IPv4);
document.getElementById('varos').value = location.city;
}
});
</script>
<!--Get Milage-->
<script>
$(function () {
$.ajax({
type: "Get",
url: "../RoadRecords/ShowMileage?licencePlate=" + "#ViewBag.LicencePlate",
success: function (data) {
$("#mileageContainer").html(data);
},
error: function (response) {
console.log(response.responseText);
}
});
});
</script>
<script>
function ConvertDouble() {
var param = $("#Fueling").val();
if (param.indexOf(".") != -1) {
param = param.replace(".", ",");
}
$("#Fueling").val(param);
}
</script>
}
Here is my full view code. I had to remove validation js because the fueling input, if I type for example 12,5 or 12.5 I got error message, so I removed it, and because of the Culture thing it's work with commas (I am from Hungary), and in the javascript I replace the dot with comma if the user type dot instead of comma.
You can add RegularExpression and ErrorMessage in your property to add rules and custom ErrorMessage
[Display(Name = "Tankolás")]
[RegularExpression(#"^[0-9]*$",ErrorMessage = "You can use numbers only")]
public double? Fueling { get; set; }
View
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Download text file via ASP.NET MVC dynamically changed

I have to generate file depending on input (checkboxes) and download it:
[HttpGet]
public FileResult GenerateFormatSettingsFile(IEnumerable<string> values)
{
var content = FileSettingsGenerator.Generate(values);
MemoryStream memoryStream = new MemoryStream();
TextWriter tw = new StreamWriter(memoryStream);
tw.WriteLine(content);
tw.Flush();
tw.Close();
return File(memoryStream.GetBuffer(), "text/plain", "file.txt");
}
And on my view this:
<button id="GenetateFormatSettingsFile" class="btn btn-primary" data-dismiss="modal" style="margin-right: 1500px">Generate</button>
$(document).ready(function() {
$("#GenetateFormatSettingsFile").click(function() {
var f = {};
var checkboxes = [];
$('input:checked').each(function() {
checkboxes.push($(this).attr("value"));
});
f.url = '#Url.Action("GenerateFormatSettingsFile", "Home")';
f.type = "GET";
f.dataType = "text";
f.data = { values: checkboxes},
f.traditional = true;
f.success = function(response) {
};
f.error = function(jqxhr, status, exception) {
alert(exception);
};
$.ajax(f);
});
});
</script>
The problem is the download doesn't start. How could I fix it?
If I do it with Html.ActionLink, the download starts, but I can't pass the values of checkboxes which is done by my ajax function above
Thanks!
Edit - that's how my check-boxes looks like:
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="modal" id="formatterSettings" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Settings</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="defaultG">To default view</label>
<input class="form-control" type="checkbox" value="Default" id="defaultG">
</div>
<div class="form-group">
<label for="extendedG">To extended view</label>
<input class="form-control" type="checkbox" value="Extended" id="extendedG">
</div>
/div>
</form>
</div>
<div class="modal-footer">
<div class="col-md-6">
<button id="GenetateFormatSettingsFile" class="btn btn-primary" data-dismiss="modal" style="margin-right: 1500px">Generate</button>
#Html.ActionLink("Generate!", "GenerateFormatSettingsFile")
</div>
<div class="col-md-6">
<a class="btn btn-primary" data-dismiss="modal" >Generate From Code</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Put a submit button in your form and POST your form synchronously (without ajax).
when a form is posted, values of all input elements (TextBoxes, CheckBoxes, ...) are sent to the server (with the request) and you don't need to do anything.

Page returns 404 error on submit using angular grid and asp.mvc

When I click submit button, I am getting a 404 error, page cannot be found.
I am using angular-ui-grid with ASP.MVC to return a list of pdfs from a Sql Server database. On the page's initial load, the grid is populated with all the pdfs and are paginated. I have added some input fields to the page so that after the initial load, you can then search by name and date range. When the button is clicked, the page returns a 404 error, cannot be found.
View
#model WSCWebsite.Models.SC_Opinions_Search_Result
#using (Html.BeginForm("Opinions", "Home", FormMethod.Post, new {#class = "form-horizontal", #id = "searchForm"}))
{
<p>Enter search information into one or more of the fields below.</p>
<p>Using more than one field will result in a more narrow search.</p>
<p>Opinions and orders published prior to 2006 are not available in this search.</p>
<div class="well" ng-controller="OpinionDefaultData">
<div class="form-group">
<label class="control-label col-sm-3">Start Date</label>
<div class="col-sm-5">
<input type="text" ng-model="StartDate" class="datefield" />
<span style="padding: 0 0 0 3px">example: 2/27/2006</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">End Date</label>
<div class="col-sm-5">
<input type="text" ng-model="EndDate" class="datefield" />
<span style="padding: 0 0 0 3px">example: 12/27/2014</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">Appellant</label>
<div class="col-sm-5">
<input type="text" ng-model="Appellant" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">Appellee</label>
<div class="col-sm-5">
<input type="text" ng-model="Appellee" />
</div>
</div>
#*<div class="form-group">
<label class="control-label col-sm-3">Docket Number</label>
<div class="col-sm-5">
<div>
#Html.TextBoxFor(m => m.DocketNumber, new { #class = "form-control", #style="display:inline-block; width:220px" })
<span style="padding: 0 0 0 3px">example: 12/27/2014</span>
</div>
</div>
</div>*#
<div class="form-group">
<div class="col-sm-4"></div>
<div class="col-sm-2">
<input type="button" value="Clear Form" onclick="history.go(0)" class="btn btn-primary" />
</div>
<div class="col-sm-2">
<button ng-click="SearchOpinions()" class="btn btn-primary">Search</button>
</div>
</div>
</div>
MVC Controller
[HttpGet]
public JsonResult GetOpinions(DateTime? StartDate, DateTime? EndDate, string Appellant, string Appellee, string DocketNumber)
{
if (EndDate != null)
{
EndDate = EndDate.Value.AddHours(23);
}
OpinionEntities dbContext = new WSCWebsite.Models.OpinionEntities();
var lst = dbContext.SC_Opinions_Search(DocketNumber,Appellant, Appellee, StartDate, EndDate, 200).ToList();
return Json(lst, JsonRequestBehavior.AllowGet);
}
Angular Controller
var app = angular.module('WSCWebSite', ['angularUtils.directives.dirPagination']);
app.controller("OpinionDefaultData", function ($scope, $http) {
$scope.StartDate = "";
$scope.EndDate = "";
$scope.Appellant = "";
$scope.Appellee = "";
$scope.DocketNumber = "";
$scope.SearchOpinions = function () {
$scope.Opinions = []; //declare an empty array
$http.get("/Home/GetOpinions", {
params: {
StartDate: $scope.StartDate,
EndDate: $scope.EndDate,
Appellant: $scope.Appellant,
Appellee: $scope.Appellee,
DocketNumber: $scope.DocketNumber
}
}).success(function (response) {
$scope.Opinions = response;
});
}
});
app.controller('OpinionData', function ($scope, $http) {
$scope.Opinions = []; //declare an empty array
$http.get("/Home/GetOpinions", {
params: {
StartDate: $scope.StartDate
, EndDate: $scope.EndDate
, Appellant: $scope.Appellant
, Appellee: $scope.Appellee
, DocketNumber: $scope.DocketNumber
}
}).success(function (response) {
$scope.Opinions = response; //ajax request to fetch data into $scope.data
});
});
your form is posting here,
#using (Html.BeginForm("Opinions", "Home", FormMethod.Post, new {#class = "form-horizontal", #id = "searchForm"}))
{
}
look here you have passed Opinions, as action but your action name is GetOpinions()
look on it, maybe it will help you..

Javascript click handlers

The task is :
I have done the form and the design bit for the web page but never came across this push: function() in javascript
I am confused on how to approach or do this task any help will be appreciated! Thank you :)
var _itq = {
push: function() {
console.log.apply(console, arguments);
}
};
_itq.push("_itq", "initialised", "ok");
<form id="commentForm" method="get" action="">
<div class="form-group">
<input class="form-control" type="email" placeholder="Enter Your Email" required>
</div>
<div class="form-group">
<div>
<input type="text" class="form-control" placeholder=" Enter Your Name" pattern=".{2,}" required title="2 characters minimum">
</div>
<div>
<input type="password" class="form-control" placeholder="Your Password" pattern=".{5,10}" required title="5 to 10 characters">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-info">Sign Up</button>
</div>
</form>
Here is the second question, this should set you on the right path for question 1.
document.getElementById('commentForm').onsubmit = function() { // attach to form submit
var email = document.getElementById("email").value; // get the email value (add id="email" to the email input in the html)
var name = document.getElementById("name").value; // get the name (add id="name" to the name input in the html)
var initials = name.split(' ').map(function(v, i) { // get the initials by splitting
return v[0] // on space and taking the 1st char
}).join('');
_itq.push(email, initials); // pass into your push
return false; // return false to stop the submit (optional depending on requirements)
};
working snippet below
var _itq = {
push: function() {
console.log.apply(console, arguments);
}
};
_itq.push("_itq", "initialised", "ok");
document.getElementById('commentForm').onsubmit = function() {
var email = document.getElementById("email").value;
var name = document.getElementById("name").value;
var initials = name.split(' ').map(function(v, i) {
return v[0]
}).join('');
_itq.push(email, initials);
return false;
};
<form id="commentForm" method="get" action="">
<div class="form-group">
<input id="email" class="form-control" type="email" placeholder="Enter Your Email" required>
</div>
<div class="form-group">
<div>
<input id="name" type="text" class="form-control" placeholder=" Enter Your Name" pattern=".{2,}" required title="2 characters minimum">
</div>
<div>
<input type="password" class="form-control" placeholder="Your Password" pattern=".{5,10}" required title="5 to 10 characters">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-info">Sign Up</button>
</div>
</form>
Try Something like this
Your HTML:
<button type="submit" class="btn btn-block btn-info" onclick="fillarr()">Sign Up</button>
JS:
function fillarr(){
_itq.push(document.getElementById("emailId").value, document.getElementById("nameId").value);
}
You still need to add an ID for your Email and Name field though

Meteor - How to create a custom field validation for a form

I want to create a custom field validation for forms using Meteor. I don't want a packaged solution.
Here is my code so far.
JavaScript:
var errorState = new ReactiveVar;
Template.lottoForm.created = function() {
errorState.set('errors', {});
};
Template.lottoForm.events({
'blur input': function(e, t) {
e.preventDefault();
validate($(this));
}
});
Template.lottoForm.helpers({
errorClass: function (key) {
return errorState.get('errors')[key] ? 'has-error' : '';
}
});
Template.errorMsg.helpers({
errorMessages: function(key) {
return errorState.get('errors');
}
});
function throwError(message) {
errorState.set('errors', message)
return errorState.get('errors');
}
function validate(formField) {
$("input").each(function(index, element){
var fieldValue = $(element).val();
if(fieldValue){
if(isNaN(fieldValue) == true) {
throwError('Not a valid Number');
}
}
});
}
HTML:
<template name="lottoForm">
<form class="playslip form-inline" role="form">
<fieldset>
<div class="form-group {{errorClass 'ball0'}}">
<input type="text" class="input-block form-control" id="ball0" maxlength="2" name="ball0">
</div>
<div class="form-group {{errorClass 'ball1'}}">
<input type="text" class="input-block form-control" id="ball1" maxlength="2" name="ball1">
</div>
<div class="form-group {{errorClass 'ball2'}}">
<input type="text" class="input-block form-control" id="ball2" maxlength="2" name="ball2">
</div>
<div class="form-group {{errorClass 'ball3'}}">
<input type="text" class="input-block form-control" id="ball3" maxlength="2" name="ball3">
</div>
<div class="form-group {{errorClass 'ball4'}}">
<input type="text" class="input-block form-control" id="ball4" maxlength="2" name="ball4">
</div>
<div class="form-group {{errorClass 'ball5'}}">
<input type="text" class="input-block form-control" id="ball5" maxlength="2" name="ball5">
</div>
{{> errorMsg}}
<div class="play-btn">
<button type="submit" value="submit" class="btn btn-primary">Play Syndicate</button>
</div>
</fieldset>
</form>
</template
<template name="errorMsg">
<div class="errorMsg">
{{#if errorMessages}}
<div class="list-errors">
{{#each errorMessages}}
<div class="list-item">{{> fieldError}}</div>
{{/each}}
</div>
{{/if}}
</div>
</template>
<template name="fieldError">
<div class="alert alert-danger" role="alert">
{{errors}}
</div>
</template>
I'm also getting this error message in the console - "Uncaught Error: {{#each}} currently only accepts arrays, cursors or falsey values."
Why do I get this error and how would I implement the custom validation?
Just as the error says, #each template functions must be passed the proper type. Are you sure your errorMessages helper is returning an array? It looks like you are initializing it as a hash.

Resources