How to load Images to Kendo grid - javascript

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);
});

Related

Passing data to stored procedure in MVC using jquery

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
});

MVC Controller JsonResult error Server cannot set content type after HTTP headers have been sent, while return

Have this function in a Controller:
public async Task<JsonResult> getTipoPerfil(int id)
{
PerfilesCalificacion pc = await db.PerfilesCalificaciones.FindAsync(id);
int ret = -1;
if (pc!=null)
{
switch (pc.Tipo)
{
case TipoCalificacion.NotaGlobal:
ret = 0;
break;
case TipoCalificacion.PerfilCalificacion:
ret = 1;
break;
default:
ret = -1; ;
break;
}
}
return new JsonResult { Data = ret };
}
In the return line above I'm getting the error.
I searched a lot but I cannot find the solution.
This function it is called by a JS function. This is part of the HTML (cshtml):
.
.
.
#Html.DropDownListFor(model => model.ApiTdEx.PerfilCalificacionId, (List<SelectListItem>)ViewBag.LstPerfiles, new { #class = "form-control", #onchange = "MuestraPerfil()" })
.
.
.
<script>
function MuestraPerfil() {
var idperfil = document.getElementById("ApiTdEx_PerfilCalificacionId").value;
$.ajax({
type: 'POST',
url: '#Url.Action("getTipoPerfil", "MenuProfesor")',
dataType: 'json',
data: { id: $("#ApiTdEx_PerfilCalificacionId").val() },
success: function (tipo) {
alert(tipo);
},
error: function (request, status, error) {
alert(error);
}
});
}
</script>
I have some code in global.asax that maybe have some relation:
private void Application_BeginRequest(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
context.Response.BufferOutput = true;
string culture = null;
if (context.Request.UserLanguages != null && Request.UserLanguages.Length > 0)
{
culture = Request.UserLanguages[0];
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(culture);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
}
}
Thanks a lot!

Jquery Ajax call does not call Asp.net mvc controller action method

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);
}

ajax call function with parameters in mvc

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");
}
});
});

Send data from textbox with ajax to asp.net mvc 5 controller

I need some help. I write little app using ASP.NET MVC5 with JavaScript, jQuery, Ajax... and I can't send data from javascript to MVC Controller and change the model.
ViewModel
public class MyViewModel
{
//...
public string SearchString { get; set; }
public int? FirstInt { get; set; }
public int? SecondInt { get; set; }
}
Javascript
function keystroke() {
var a = 0, b = 0;
$('#search').keyup(function (event) { a = 1; });
$('#search').keydown(function (event) { b = 1; });
$("#search").keypress(function (event) {
if (e.which === 13) {
e.preventDefault();
$('form').click(function () {
sendForm(a, b);
});
}
});
};
function sendForm(a, b) {
$.ajax({
url: #Url.Action("Index", "Home"),
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
FirstInt: a,
SecondInt: b
}),
success: function () {
alert('success');
}
});
};
View
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { #class = "form-inline", role = "form" }))
{
<div class="form-group has-feedback">
#Html.TextBox("SearchString", ViewBag.SearchFilter as string, new
{
#class = "form-control",
onclick="keystroke()",
id = "search"
})
</div>
}
Controller
public async Task<ActionResult> Index(MyViewModel model)
{
//...
if (model.SearchString != null)
{
//...
var a = model.FirstInt;
var b = model.SecondInt;
}
//...
return View(model);
}
Help me, please, to send all the values to controller. Those that changed in JavaScript and what I enter in the textbox. Thanks.
Javascript Code:
function keystroke() {
var a = 0, b = 0;
$('#search').keyup(function (event) { a = 1; });
$('#search').keydown(function (event) { b = 1; });
$("#search").keypress(function (event) {
if (e.which === 13) {
e.preventDefault();
$('form').click(function () {
var text = $("#search").val()
sendForm(a, b, text);
return false;
});
}
});
};
function sendForm(a, b, text) {
var data = {FirstInt: a,SecondInt: b,SearchString: text}
$.ajax({
url: 'Home/Index',
type: 'POST',
contentType: 'application/json',
data: data,
success: function () {
alert('success');
}
});
};
Controller Code
[HttpPost]
public async Task<ActionResult> Index(MyViewModel model)
{
//...
if (model.SearchString != null)
{
//...
var a = model.FirstInt;
var b = model.SecondInt;
}
//...
return View(model);
}

Categories

Resources