i am creating the Asp.net MVC Project in Bank Balance Checking.if i enter the correct account no relevant balance want to display but not not displayed while i am running the programming i got the error was Additional information: The underlying provider failed on Open.
what i tried so far i attached below.
Index.cshtml
#{
ViewBag.Title = "Index";
}
<div class="row">
<div class="col-sm-8">
#using (Html.BeginForm("Index", "home", FormMethod.Post, new { id = "popupForm" }))
{
<table class="table table-bordered">
<caption> Add Products </caption>
<tr>
<th>Account No</th>
<th>Account Holder Name</th>
<th>Balance</th>
</tr>
<tr align="center">
<td>
<input type="text" class="form-control" placeholder="Account No" id="accno" name="accno" size="50px">
</td>
<td>
<input type="text" class="form-control" id="accname" size="25px" name="accname"
placeholder="price" disabled>
</td>
<td>
<input type="number" class="form-control" id="balance" name="balance"
placeholder="qty" size="25px" required>
</td>
</tr>
</table>
}
</div>
</div>
<hr />
#Scripts.Render("~/bundles/jquery")
#section scripts{
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.js"></script>
<script>
getProductcode();
function getProductcode()
{
$("#accno").empty();
$("#accno").keyup(function (e) {
var q = $("#accno").val();
if ($('#accno').val().length === 0) {
$.alert({
title: 'Error!',
content: "Please Enter the Barcode",
type: 'red',
autoClose: 'ok|2000'
});
return false;
}
$.ajax({
type: "POST",
url: '/home/Getid?id=' + $("#accno").val(),
dataType: "JSON",
success: function (data)
{
console.log(data);
$('#accname').val(data.accname);
$('#balance').val(data.balance);
},
error: function (xhr, status, error)
{
// alert("The barcode entered is not correct");
}
});
return true;
});
}
</script>
}
#section styles{
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.css">
<link rel="stylesheet" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
}
HomeController
//you don't need this here except you want to use Dependency injection
bankEntities dc = new bankEntities();
public ActionResult Index()
{
return View();
}
public string accno { get; set; }
[HttpPost]
public JsonResult Getid(String Id)
{
var std = dc.accounts.Where(a => a.accno == Id).FirstOrDefault();
return Json(std, JsonRequestBehavior.AllowGet);
}
}
Related
I have one drop down box. Based on the selected item of dropdownbox i want to generate form below on same view, Please find the code below.
[HttpGet]
public ActionResult BindDropDown()
{
ViewBag.doctype = new SelectList(db.DocTypeMasters, "Id", "DocTypeName");
return View();
}
[HttpPost]
public ActionResult BindDropDown(string DocType)
{
String Doc = DocType.Trim();
return View();
}
this is my view code
#model C3CardKYC.Models.DocTypeMaster
#{
ViewBag.Title = "BindDropDown";
}
<h2>BindDropDown</h2>
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#MyIdAndName').change(function () {
var DocType = $("#MyIdAndName option:selected").text();
alert(DocType);
$.ajax({
url: '#Url.Action("BindDropDown", "Document")',
type: 'POST',
data: { DocType: DocType },
success: function (result) {
alert('success')
}
})
});
});
</script>
<fieldset>
<legend>DocTypeMaster</legend>
#*Select Document Type: #Html.DropDownList("doctype", "Select");*#
#Html.DropDownList("MyIdAndName", ViewBag.doctype as SelectList, " -- Select Document Type -- ")
</fieldset>
<p id="hi">
#Html.ActionLink("Back to List", "Index")
</p>
<div id="hi">
#using (Html.BeginForm("BindDropDown", "Document", FormMethod.Post, new { id = "submitForm" }))
{
<fieldset>
<ol>
<li>
#Html.LabelFor(Model => Model.DocTypeName)
#Html.TextBoxFor(Model => Model.DocTypeName, new { maxlength = 50 })
#Html.ValidationMessageFor(Model => Model.DocTypeName)
</li>
</ol> <button type="submit" id="btnSave" name="Command" value="Save">Save</button>
<button type="submit" id="btnSubmit" name="Command" value="Submit">Submit</button>
<button type="submit" id="btnCancel" name="Command" value="Cancel" onclick="$('#submitForm').submit()">Cancel (Server Side)</button>
</fieldset>
}
</div>
When i run this below error is coming.
There is no ViewData item of type 'IEnumerable' that has the key 'MyIdAndName'.
and if i select the item frm dropdown then only below form should appear. Please suggest
I am trying to figure out ,why my validation messages are not showing up?
Here is my Razor page
#model MyViewModel
#{
Layout = "~/Views/Shared/_MainLayout.cshtml";
var listErrors = ViewBag.listErrors as Array;
}
<section class="selectconfiguration">
<h3 class="active">Add Rule</h3>
<div class="con-section">
#{Html.EnableClientValidation(true);}
#{Html.EnableUnobtrusiveJavaScript();}
#using (Html.BeginForm("AddRules", "Aliases", "HttpPost"))
{
#Html.ValidationSummary(true)
<table>
<tr>
<td class="phone-options-label-column">
<div class="editor-label">
#Html.Label("Alias String:")
</div>
</td>
<td>
#Html.EditorFor(m => m.AliasString,new {#id="txtAliasString"})
</td>
<td> #Html.ValidationMessageFor(m => m.AliasString)</td>
</tr>
<tr>
<td class="options-label-column">
<div class="editor-label">
#Html.Label("Select an Associated Model:")
</div>
</td>
<td>
#Html.DropDownList("ddlModels", new SelectList(Model.Models, "Id", "Name", ""), "Unknown", new { #class = "mselectDDContItem" })
</td>
<td>
</td>
</tr>
</table>
}
<div>
<input type="submit" value="Add Rule" id="btnAddRule" name="AddRule" />
</div>
</div>
</section>
Here is my ViewModel
public class MyViewModel
{
[Required(ErrorMessage = "alias string required")]
[StringLength(30, ErrorMessage = "AliasString cannot be larger than 30 characters")]
public string AliasString { get; set; }
public IEnumerable<IParameter> Models { get; set; }
public string StatusMessage { get; set; }
}
On clciking the addRules button triggers my jquery clcik event
<script type="text/javascript">
$(document).ready(function () {
$("#btnAddRule").click(function (e) {
e.preventDefault();
var params = {
'aliasString': $("#txtAliasString").val(),
'modelId': $("#ddlModels").val()
};
$.ajax({
url: "/Aliases/AddRules",
type: "POST",
dataType: 'json',
data: JSON.stringify(params),
async: false,
cache: false,
traditional: true,
contentType: 'application/json',
}).done(function () {
}).complete(function () {
}).success(function (dv) {
});
});
});
</script>
and I have these script references also on my layout page
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.treeview.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.ui.selectmenu.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/global.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.nad.session.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcValidation.js")"></script>
I dont understhnad why the validations are not firing.
If I click the button with the empty textbox also ,I can see post back happens and modelstate.isValid is returning true to the controller.
In my jquery button click function ,I added ,$('#myForm').valid() and then my validation started showing up.
$("#btnAddRule").click(function (e) {
if ($('#myForm').valid()) {
}
});
Just put submit button inside the form and validation would work
I have an Area like below.
Controller Class
public class AdminController : Controller
{
//
// GET: /Admin/Admin/
[HttpPost]
public ActionResult Index_partialPost(AdminModule model)
{
return PartialView("_PartialPage1", model);
}
[HttpGet]
public ActionResult Index_partial()
{
return PartialView("_PartialPage1");
}
[HttpGet]
public ActionResult Index()
{
AdminModule model = new AdminModule();
model.MyName = "My Name";
return View("Index", model);
}
}
View
#model _1.Areas.Admin.Models.AdminModule
#{
ViewBag.Title = "Index";
Layout = "~/Areas/Admin/Views/Shared/_LayoutPage1.cshtml";
}
<h2>
Index</h2>
<div id="myForm">
<p id="pid">
</p>
</div>
<input id="BTN" type="submit" value="Button" />
<script language="javascript" type="text/javascript">
$('#BTN').click(function(){
$('#pid').load("#Url.Action("Index_partial", "Admin")");
});
</script>
View
#model _1.Areas.Admin.Models.AdminModule
#{
ViewBag.Title = "Index";
Layout = "~/Areas/Admin/Views/Shared/_LayoutPage1.cshtml";
}
<h2>
Index</h2>
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript">
</script>
<div id="myForm">
<p id="pid">
</p>
</div>
<input id="BTN" type="submit" value="Button" />
<script language="javascript" type="text/javascript">
$('#BTN').click(function(){
$('#pid').load("#Url.Action("Index_partial", "Admin")");
});
</script>
Partial View
#model _1.Areas.Admin.Models.AdminModule
#using (Html.BeginForm())
{
#Html.LabelFor(i => i.MyName)
#Html.TextBoxFor(i => i.MyName)
#Html.ValidationMessageFor(i => i.MyName)
<p id="getDateTimeString">
</p>
<input type="submit" value="Click here" id="btn" />
}
<script language="javascript" type="text/javascript">
$('#btn').click(function () {
var url = '#Url.Action("Index_partialPost", "Admin")';
$.post(url, null, function (data) {
});
});
</script>
Issue is - When trying to post the partial view using jQuery-post not working and giving 404. It's working with Ajax using below mentioned code of Partial View
#model _1.Areas.Admin.Models.AdminModule
#using (Ajax.BeginForm("Index", "Admin",
new AjaxOptions { UpdateTargetId = "myForm", HttpMethod = "Post" }))
{
#Html.LabelFor(i => i.MyName)
#Html.TextBoxFor(i => i.MyName)
#Html.ValidationMessageFor(i => i.MyName)
<p id="getDateTimeString">
</p>
<input type="submit" value="Click here" id="btn" />
}
You should cancel the default action of the form by returning false from your click handler:
<script type="text/javascript">
$('#btn').click(function () {
var url = '#Url.Action("Index_partialPost", "Admin")';
$.post(url, null, function (data) {
});
return false;
});
</script>
If you don't do that, the form is submitted to the server and the browser redirects to the target url leaving you absolutely no time for your AJAX request to ever execute.
Notice that it is much better to subscribe to the .submit event of the form in order to perform the AJAX request instead of the .click event of the submit button. The reason for this is obvious: there are other means to submit a form than clicking on a submit button. For example pressing the Enter key while inside an input field. If this happens your AJAX will never execute.
So here's the correct way. Start by giving an unique id to your form:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
#Html.LabelFor(i => i.MyName)
#Html.TextBoxFor(i => i.MyName)
#Html.ValidationMessageFor(i => i.MyName)
<p id="getDateTimeString">
</p>
<input type="submit" value="Click here" id="btn" />
}
and then you could unobtrusively AJAXify this form:
<script type="text/javascript">
$('#myForm').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
}
});
return false;
});
</script>
I think you need to define the Area in the routeparameter where you do #Url.Action in your partial view:
$('#btn').click(function () {
var url = '#Url.Action("Index_partialPost", "Admin", new { area = "Admin"})';
$.post(url, null, function (data) {
});
});
Else it will be posted to your main (root) Area where you probably don't have a AdminController...
You can doublecheck the url in the JS your HTML source when the form is rendered, it sould read "/Admin/Admin/Index_partialPost" instead of just "/Admin/Index_partialPost"
I am trying to show a DataTable in HTML table through knockout binding...I dont know where i am missing or wrong:
My Controller:
public JsonResult GetEmployees()
{
BAL.Employee dbProvider = new BAL.Employee();
DataTable dataTable = dbProvider.ShowEmployeeDetails();
List<Model.Employee> objExerciseList = new List<Model.Employee>();
foreach (DataRow dataRow in dataTable.Rows)
{
Model.Employee objExercise = new Model.Employee();
objExercise.EmployeeCode = dataRow["EmpCode"].ToString();
objExercise.EmployeeName = dataRow["EmpName"].ToString();
objExerciseList.Add(objExercise);
}
return Json(objExerciseList, JsonRequestBehavior.AllowGet);
}
My Model:
public class Employee
{
private string employeeCode;
private string employeeName;
public int ID { get; set; }
[Required(ErrorMessage="Employee Code is Required")]
public string EmployeeCode
{
get
{
return employeeCode;
}
set
{
employeeCode = value;
}
}
[Required(ErrorMessage = "Employee Name is Required")]
public string EmployeeName
{
get
{
return employeeName;
}
set
{
employeeName = value;
}
}
}
This is my ViewModel Code:
#{
ViewBag.Title = "Exercise9";
Layout = "../Shared/Master.cshtml";
}
<html>
<head>
<title>KO</title>
<script src="../../Scripts/jquery-1.6.2.js" type="text/javascript"></script>
<script src="../../Scripts/knockout-2.2.1.js" type="text/javascript"></script>
<script src="../../Scripts/knockout.mapping-latest.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
<form action="" method="get">
<div style="width: 990px; background-color: White; height: 710px;">
<table id="tbllist" align="center" style="border:5px #fff solid;">
<tr>
<td colspan="6">
<h2>
Employee List</h2>
</td>
</tr>
<tr>
<td colspan="6" style="padding: 0px;">
<div id="title_p">
Listing</div>
</td>
</tr>
<tr>
<th align="left">
Employee Code
</th>
<th align="left">
Employee Name
</th>
</tr>
<tbody data-bind="foreach: Employees">
<tr style="border-bottom: 1px solid #000000;">
<td>
<span data-bind="text: EmployeeCode"></span>
</td>
<td>
<span data-bind="text: EmployeeName"></span>
</td>
</tr>
</tbody>
</table>
</div>
</form>
<script type="text/javascript">
var EmpViewModel = function () {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.EmployeeCode= ko.observable("0");
self.EmployeeName= ko.observable("");
//The Object which stored data entered in the observables
var EmpData = {
EmpCode:self.EmployeeCode,
EmpName: self.EmployeeName
};
//Declare an ObservableArray for Storing the JSON Response
self.Employees = ko.observableArray([]);
GetEmployees(); //Call the Function which gets all records using ajax call
//Function to Read All Employees
function GetEmployees() {
//Ajax Call Get All Employee Records
$.ajax({
type: "GET",
url: "/Exercise/GetEmployees/",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.Employees(data); //Put the response in ObservableArray
},
error: function (error) {
alert(error.status + "<--and--> " + error.statusText);
}
});
//Ends Here
}
};
ko.applyBindings(new EmpViewModel());
</script>
Please help me...THANKS IN ADVANCE....!!
Give it a try to convert from Json to observable JavaScript model as follow :
$.ajax({
type: "GET",
url: "/Exercise/GetEmployees/",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
ko.mapping.fromJS(data, {}, self.Employees);
},
error: function (error) {
alert(error.status + "<--and--> " + error.statusText);
}
});
i am having a problem with validating a form in MVC Razor the Binding class is the following based off an abstract class (there is no validation in the abstract class)
[GeminiDisplayName("You are about To reject the following Purchase Order", false)]
public class PORejected : PoApprovalItems
{
public PORejected() { }
[GeminiDisplayName("Rejection Reason")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Rejection Reason is Required")]
public string RejectReason { get; set; }
public override bool IsApproved
{
get
{
return false;
}
}
}
and the view is as follows
#model Gemini.Models.PORejected
#section Head{
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcValidation.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/PageScripts/_Approval.js")" type="text/javascript"></script>
}
#section TabHeader{
<li>Reject Approval for PO #Model.PO_Number</li>
}
#section TabContent{
#{
Html.EnableClientValidation();
}
<div id="ApprovalItem">
#{
#Html.ValidationSummary(false)
using (Html.BeginForm("Approve", "PO", FormMethod.Post))
{
#Html.Partial("Approval/ApprovalDetails", Model)
<div class="display-label">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td width="15%">
#Html.LabelFor(x => x.RejectReason)
</td>
<td>
#Html.TextAreaFor(x => x.RejectReason, new { #Class = "mceEditor required", #style = "width:60%;" })
#Html.ValidationMessageFor(x => x.RejectReason)
</td>
</tr>
</table>
<div style="float: right;">
<input type="button" value="Close" />
<input type="submit" value="Reject" />
</div>
</div>
Html.EndForm();
}
}
</div>
}
the thing is when i click the submit button it fires off before doing any validation even though it should validate
my question is what am i doing wrong?
UPDATED
found the answer eventually i was missing the following from the page.
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
found the answer eventually i was missing the following from the page. <script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
What is this line for?
Html.EnableClientValidation(false);
This disables client validation. Also, no need to set UnobtrusiveParameters on each view, set them once in web config.