I'm new to Jquery. I want to pass data to my SQL database via Ajax.
Inside the Controller:
GetCountry Method Gets list of countries from the database proc
public JsonResult GetCountries()
{
using(var db = GetContxt())
{
var eventCountries = db.Database.SqlQuery<LocationModel>(String.Format("Location.spGetCountries")).ToList();
return new JsonResult { Data = eventCountries, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
And a method that sends data to the database:
[HttpPost]
public JsonResult SavePatient(LocationModel locationModel)
{
string connection = ConfigurationManager.ConnectionStrings["EnrollmentEntity"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connection))
{
SqlCommand cmd = new SqlCommand("Profile.spAddPatientProfile", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#FirstName", locationModel.FirstName));
cmd.Parameters.Add(new SqlParameter("#LastName", locationModel.LastName));
cmd.Parameters.Add(new SqlParameter("#IDNumber", locationModel.ID_Number));
cmd.Parameters.Add(new SqlParameter("#Line1", locationModel.Line1));
cmd.Parameters.Add(new SqlParameter("#Line2", locationModel.Line2));
cmd.Parameters.Add(new SqlParameter("#CountryIDFK", Int32.Parse(locationModel.CountryIDFK)));
cmd.Parameters.Add(new SqlParameter("#Message", SqlDbType.VarChar, 250)).Direction = ParameterDirection.Output;
try
{
conn.Open();
cmd.ExecuteNonQuery();
locationModel.Message = Convert.ToString(cmd.Parameters["#Message"].Value);
conn.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
return new JsonResult { Data = locationModel, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
Now this is my Ajax method that i want to send data to my controller method
function SaveButton()
{
$.ajax({
url: "/Home/SavePatient",
type: "POST",
data: $("#frmHome").serialize(),
async: false,
error: function (xhr, status, error)
{
alert("was not successful xhr: " + xhr.value + " status: " + status.value + " error: " + error.value);
},
success: function (Record)
{
alert("was successful");
}
})
}
These are my HTML elements textboxfor and dropdownListfor
#{
ViewBag.Title = "Home Page";
}
#using PatientEnrollmentVS.Models;
#model LocationModel
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
#using (Html.BeginForm("SavePatient", "Home", FormMethod.Post, new { #id = "frmHome" }))
{
<div class="row">
<label>First Name</label>
#Html.TextBoxFor(x => x.FirstName, new { #class = "select-block" })
<label>Last Name</label>
#Html.TextBoxFor(x => x.LastName, new { #class = "select-block" })
</div>
<div class="row">
<label>ID Number</label>
#Html.TextBoxFor(x => x.ID_Number, new {#class = "select-block"})
</div>
<div class="row">
<label>DateOfBirth</label>
#Html.TextBoxFor(x => x.DateOfBirth, new { #class = "select-block" })
</div>
<div class="row">
<label>Countries</label>
#Html.DropDownListFor(x => x.CountryId, new List<SelectListItem>()
{ new SelectListItem()
{
Value = Model.CountryId,
Text = Model.CountryName,
Selected = true
}
}, "0", new { id = "dllGetCountries", #class = "select-block", name = "Countries" })
</div>
<div class="row">
<input type="button" value="Save Event" class="btn btn-primary" onclick="SaveButton()" />
</div>
var valdata = $("#frmHome").serialize();
$.ajax({
url: "/Controller/Method",
type: "POST",
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: valdata
});
Related
I CANNOT CREATE CASCADING DROPDOWN IN ACTIONRESULT CREATE, ONLY IN ACTION RESULT INDEX IT WORKS
THERE GOES THE CODE
CONTROLLER
public class PessoasController : Controller
{
private GestarkContext db = new GestarkContext();
// GET: Pessoas
public ActionResult Index()
{
ViewBag.Gabinetes = new SelectList(db.Gabinetes, "GabineteId", "Nome");
var pessoageral = db.Pessoas.Include(a => a.gabojecto).Include(a => a.nivelojecto);
return View(pessoageral.ToList());
}
[HttpPost]
public JsonResult getDistricts(int gbtID)
{
List<Departamento> DepartamentoList = db.Departamentoes.Where(p => p.GbtId == gbtID).ToList();
return Json(DepartamentoList, JsonRequestBehavior.AllowGet);
}
VIEW INDEX - IT WORKS HERE
<script>
$(function () {
$('#Gabinetes').change(function () {
var gbtID = $(this).val();
$.ajax({
type: "post",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "getDistricts",
data: "{gbtID:'" + gbtID + "'}",
success: function (data) {
$('#DepartamentoList').empty();
$('#DepartamentoList').append('<option selected="selected" value="">Select Departamento</option>')
$.each(data, function (i, d) {
$('#DepartamentoList').append('<option value=' + d.DircId + '>' + d.Depto + '</option>');
});
},
failure: function (data) {
alert('error occured');
}
});
});
});
</script>
<h2>Lista de Funcioários Registrados</h2>
<br />
<label class="col-md-2 control-label">Gabinete</label>
<div class="col-md-5">
#Html.DropDownList("Gabinetes", null, htmlAttributes: new { #class = "form-control" })
</div>
<div class="form-group">
<label class="col-md-2 control-label">Departamento</label>
<div class="col-md-4">
<select id="DepartamentoList" name="DepartamentoList" class="form-control"></select>
</div>
</div>
<p>
#Html.ActionLink("Visualizar Formulário", "Index", "Principal", null, new { #class = "btn btn-default" }) | #Html.ActionLink("Adicionar Novo", "Create", null, new { #class = "btn btn-primary" }) | #Html.ActionLink("Exportar em Excel", "ExportToExcel", null, new { #class = "btn btn-success" })
</p>
...........
NOW ON VIEW CREATE DOES NOT WORK
I write the code as I do in index, but it doesn't work
I NEED YOUR HELP PLEASE
I am uploading image to the network folder which is not inside the project. Uploading images works 100%. The challenge is to read those image back to the grid, i am struggling to read all the images to Kendo grid.
**Question : How can i read images from network folder to Kendo grid **
This is what i have tried,
Reading Folder Url from the config
string Filelocation = System.Configuration.ConfigurationManager.AppSettings["Home.Settings"];
Model
public class SettingsModel
{
[DataType(DataType.Upload)]
public HttpPostedFileBase UploadImage { get; set; }
public string ImageUrl { get; set; }
}
Uploading Controller
[HttpPost]
[CustomAuthorize]
public ActionResult SaveBackgroundImage(SettingsModel model)
{
try
{
string backgroundImg = "";
string ImageName = "";
if (model.UploadImage != null)
{
backgroundImg = Path.GetFileName(model.UploadImage.FileName);
string e = Path.GetExtension(backgroundImg);
if (model.UploadImage != null)
{
ImageName = Path.Combine(Filelocation, backgroundImg);
model.UploadImage.SaveAs(ImageName);
model.ImageUrl = Url.Content(Path.Combine(Filelocation, ImageName)); // saving the Image url,wanted to try to read url
}
}
return View("BackgroundImage", model);
}
catch (Exception ex)
{
return Json(new { result = false, errormsg = "Error: " + ex.Message });
}
}
I got this url after saving:
\\0.0.0.000\Main\HomeSettings\BackgroundImage\20170802_174049.jpg
View
#using (Ajax.BeginForm("SaveBackgroundImage", "BackgroundSettings", new AjaxOptions { HttpMethod = "Post" }, new { #class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
{
<div class="form-group">
<label class="control-label col-sm-2" for="txtfrom">Upload Image:</label>
<div class="col-md-4">
#Html.TextBoxFor(m => m.UploadImage, new { type = "file", #id = "id_fileUploadImage", #class = "form-control input-sm", required = "required", #accept = ".jpg,.png,.gif" })
</div>
<br /><br />
<div class="col-sm-10 col-sm-offset-2">
<button class="btn btn-primary " id="btnSaveFile" name="submit" type="submit">Upload Image</button>
</div>
</div>
#(Html.Kendo().Grid<TTAF.Portal.Parts.Web.Models.SettingsModel>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(c => c.ImageUrl).ClientTemplate("<img src='" + Url.Content(Model.ImageUrl) + "#=ImageUrl#' alt='#=Name #' Title='#=Name #' height='62' width='62'/>");
//Error here: {"Object reference not set to an instance of an object."}
})
.Pageable(pageable => pageable
.Refresh(true))
.Scrollable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(1)
.ServerOperation(false) //No post back
.Read(read => read.Action("", ""))))
}
Script
$(document).ready(function () {
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) {
var obj = JSON.parse(xhr.responseText)
if (obj.result == true) {
var ObjResults =
{
UploadImage: obj.UploadImage
}
alert(obj.UploadImage);
$.ajax({
url: '#Url.Action("SaveBackgroundImage", "BackgroundSettings")',
data: ObjResults,
type: "Post",
crossDomain: true,
async: true,
cache: true,
success: function (data) {
if (data.result == true) {
alert("Image Uploaded");
}
else {
alert("Error Occured");
}
}
});
}
else {;
}
}
};
xhr.send(new FormData(form));
}
}
}, true);
});
I have two drop-downs State and City.According to State selected city should be loaded.So I use State drop-down change event to call ajax method to populate City drop-down.
HTML
<div class="row">
<div class="col-sm-6 ">
<div class="form-group">
<label>State</label>
#Html.DropDownListFor(m => m.State, Model.States, "Please select a State", new { #class = "form-control" })
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 ">
<div class="form-group">
<label>Cities</label>
#Html.DropDownListFor(m => m.CityRegisterScreen, new SelectList(string.Empty, "Id", "Name"), "Please select a city", new { #class = "form-control" })
</div>
</div>
</div>
JavaScript
This Contains Jquery and Javascript Code.
$(document).ready(function () {
$("#State").on("change", function () { // whenever a selection is made
$("#CityRegisterScreen").empty();
var id = $("#State").val();
$.ajax({
type: 'GET', // we are calling json method
url: '#Url.Action("GetCitiesByDistrict", "Account")',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { id: id },
success: function (cities) {
$.each(cities, function (i, city) {
$("#CityRegisterScreen").append('<option value="' + city.value + '">' +
city.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve cities.' + ex);
}
});
return false;
});
});
Controller
This is the controller action method which returns Json
public JsonResult GetCitiesByDistrict(int id)
{
List<SelectListItem> cities = new List<SelectListItem>();
var city = new List<City>();
using (ApplicationDbContext context = new ApplicationDbContext())
{
city = context.Cities.Where(e => e.DistrictId == id).ToList();
}
return Json(new SelectList(city, "Id", "Name"), JsonRequestBehavior.AllowGet);
}
Issue is when ajax method is called it doesn't call the Action method in controller.I double checked the URL and DataType it's all perfect.But Action method didn't get called.
It is silly!!! How did i miss this. Thank You #Rajshekar Reddy for your comment it guided me. I am missing [AllowAnonymous] attribute.
[AllowAnonymous]
public JsonResult GetCitiesByDistrict(int id)
{
List<SelectListItem> cities = new List<SelectListItem>();
var city = new List<City>();
using (ApplicationDbContext context = new ApplicationDbContext())
{
city = context.Cities.Where(e => e.DistrictId == id).ToList();
}
return Json(new SelectList(city, "Id", "Name"), JsonRequestBehavior.AllowGet);
}
This is a code for loading States according to selected country. Try this solution.
HTML
#Html.DropDownListFor(model => model.CustAddr_Country_ID, Model.Countries, "Select Country", htmlAttributes: new { #class = "disableInput", #id = "ddlstate", #onchange = "javascript:GetCity(this.value);" })
#Html.DropDownListFor(model => model.CustAddr_State_ID, ViewBag.CustAddr_State_ID as SelectList, "Select State", htmlAttributes: new { #class = "disableInput"})
Script
function GetCity(_stateId) {
$("#CustAddr_State_ID").empty().trigger('change');
var newOption = new Option("Select State", 0, true, true);
$("#CustAddr_State_ID").append(newOption).trigger('change');
if (_stateId != null && _stateId != "") {
var url = "/Ajax/GetCityByStaeId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
for (var x = 0; x < data.length; x++) {
var newOption = new Option(data[x].Text, data[x].Value, true, true);
$("#CustAddr_State_ID").append(newOption).trigger('change');
}
$('#CustAddr_State_ID').val('0').trigger('change');
},
error: function (reponse) {
//alert("error : " + reponse);
}
});
}
}
Controller
[HttpPost]
public ActionResult GetCityByStaeId(int stateid)
{
List<State> objcity = new List<State>();
objcity = _state.GetState().Where(m => m.State_Country_ID == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "State_ID", "State_Name", 0);
return Json(obgcity);
}
I am very new to this, what I am trying to do is use ajax to call a controller function from view, this is my controller.
public ActionResult EditSiteGetContact(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
using (var db = SiteUtil.NewDb)
{
var owner = db.Contacts.Include(o => o.Id).FirstOrDefault(o => o.Id == id);
if (owner == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var orgViewModel = OrgViewModel.ToViewModel(owner);
return View("Edit", orgViewModel);
}
}
and this is the view where I want to show the data
<div class="form-group" id="alanTest">
<label class="control-label col-md-2">Contact Person</label>
<div class="col-md-6 form-inline">
#Html.TextBoxFor(model => model.Owner.Name, new { #class = "form-control", style = "width:200px", type = "text" })
<img src="~/Images/help-icon.png" class="tooltips" id="ContactPerson_Tooltip" title="lol">
#Html.ValidationMessageFor(model => model.Owner.Name)
</div>
</div>
my ajax part:
$("#alanTest").ready(function(){
var alanURL = "#Url.Action("EditSiteGetContact","Org")";
var contactId = #Model.Org.ContactId;
$.ajax({
type:"POST",
url:alanURL,
data:{
id:contactId
},
success:function(data){
alert(data);
},
error: function(){
alert("error");
}
});
});
i got "error" message..
Add [HttpPost] attribute before EditSiteGetContact(int? id).
In the ajax function change
var contactId = #Model.Org.ContactId; to var contactId = "#Model.Org.ContactId";
Please see below code. It may help you.
$("#alanTest").ready(function(){
var alanURL = "#Url.Action("EditSiteGetContact","Org")";
var contactId = "#Model.Org.ContactId";
$.ajax({
type:"POST",
url:alanURL,
data:{
id:contactId
},
success:function(data){
alert(data);
},
error: function(){
alert("error");
}
});
});
I created cascading drop-down list as shown in the picture
here the view
here the cshtml code snippet
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.HEI_ID)
#Html.Label("*", new { id="star" , #class = "requiredFiledCol" })
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.HEI_ID, (SelectList)ViewBag.UniversityList_New, "Select University / Institute", new {id="University", #class = "form-control" })
#Html.ValidationMessageFor(model => model.HEI_ID)
</div>
</div>
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.COL_ID)
#Html.Label("*", new { id="star" , #class = "requiredFiledCol" })
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.COL_ID, (SelectList)ViewBag.FacultyList_New, "Select College", new {id="College", #class = "form-control" })
#Html.ValidationMessageFor(model => model.COL_ID)
</div>
</div>
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.DEP_ID)
#Html.Label("*", new { id="star" , #class = "requiredFiledCol" })
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.DEP_ID, (SelectList)ViewBag.DepartmentList_New, "Select Department", new { id="Department" , #class = "form-control" })
#Html.ValidationMessageFor(model => model.DEP_ID)
</div>
</div>
This is jquery code snippet
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#University").change(function () {
$("#College").empty();
$("#Department").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetColleges")', // we are calling json method
dataType: 'json',
data: { uni_id: $("#University").val() },
success: function (Colleges) {
$.each(Colleges, function (i, state) {
$("#College").append('<option value="' + state.Value + '">' + state.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
$("#College").change(function () {
$("#Department").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetDepartments")', // we are calling json method
dataType: 'json',
data: { col_id: $("#College").val() },
success: function (Departments) {
$.each(Departments, function (i, state) {
$("#Department").append('<option value="' + state.Value + '">' + state.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
But in last dropdown (department drop down) its not populate , how can I overcome this
this is the action methods related to this module
public JsonResult GetColleges(string uni_id)
{
var Colleges = from college in db.Colleges
where college.HEI_ID == uni_id & college.Status == true
select college;
//List<SelectListItem> states = new List<SelectListItem>();
return Json(new SelectList(Colleges.ToList(), "College_ID", "College_Name"));
}
public JsonResult GetDepartments(string col_id)
{
var Departments = from department in db.Departments
where department.College_ID == col_id & department.Status == true
select department;
//List<SelectListItem> states = new List<SelectListItem>();
return Json(new SelectList(Departments.ToList(), "Department_ID", "Name_of_Department"));
}
I tried out your code and it is working for me fine but not when you have only one item returned and populated in the College dropdown. That is because change() will not be fired if you have only 1 item and you select that. So to avoid what you can do is when cascade load data in dropdown add a option label so that user has to select a valid option and change gets fired and thus, Department dropdown get loaded with data. So your College change can look like this:
$("#College").change(function () {
$("#Department").empty();
//If option label was selected then do not send request
if ($("#College").val() == 0)
{
return;
}
$.ajax({
type: 'POST',
url: '#Url.Action("GetDepartments")',
dataType: 'json',
data: {
col_id: $("#College").val()
},
success: function (Departments) {
//Add option label as the first element (selected by default)
$("#Department").append('<option value="0">-SELECT COLLEGE-</option>');
$.each(Departments, function (i, state) {
$("#Department").append('<option value="' + state.Value + '">' + state.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
});
NOTE: Changes indicated with comment above code