I submit a form to take objects from database.
I need to add varbinary(MAX) type (image) column inside json string, and send it via WebMethod to Ajax to display in the page, with the rest of the properties of the object. So in the class its string type instead of byte[] type.
In the encoding part I receive Javascript runtime Error:
Unable to get property 'pingInterval' of undefiened null reference.
<form id="form1" runat="server">
Arrival:
<input type="text" id="txtArrival" />
departure:
<input type="text" id="txtDeparture" />
Nob:
<input type="text" id="txtNob" />
<input type="button" id="btnSubmit" value="Get Rooms" />
</form>
Class:
public int ID { get; set; }
public string RoomType { get; set; }
public string RoomNumber { get; set; }
public string RoomTitle { get; set; }
public decimal Price { get; set; }
public string ServiceName { get; set; }
public string Photo { get; set; }
Ajax:
$(document).ready(function () {
$(function () {
$("#btnSubmit").click(function () {
var arrival = $("#txtArrival").val();
var departure = $("#txtDeparture").val();
var nob = $("#txtNob").val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm2.aspx/GetRooms",
data: "{'arrival':'" + arrival + "','departure':'" + departure + "','nob':'" + nob + "'}",
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function (result) {
alert("Error!");
}
});
});
});
});
WebMethod:
[WebMethod]
public static string GetRooms(string arrival, string departure, string nob)
{
string val = "";
DateTime d1 = Convert.ToDateTime(arrival);
DateTime d2 = Convert.ToDateTime(departure);
int noib=Convert.ToInt32(nob);
var jSerialize = new JavaScriptSerializer();
List<Room> lst = new List<Room>();
using (SqlConnection con = new SqlConnection("Server=.;Database=ResDB;Trusted_Connection=True;"))
{
using (SqlCommand cmd = new SqlCommand("roomsAvailable", con))
{
cmd.Parameters.AddWithValue("#arr", d1);
cmd.Parameters.AddWithValue("#dep", d2);
cmd.Parameters.AddWithValue("#nob", noib);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader sr = cmd.ExecuteReader(); ;
while (sr.Read())
{
Room r = new Room();
r.ID = Convert.ToInt32(sr["ID"]);
//objects..
if (sr["Photo"] != System.DBNull.Value)
{
byte[] p = (byte[])sr["Photo"];
r.Photo = Convert.ToBase64String(p);// error here
}
lst.Add(r);
val = jSerialize.Serialize(lst);
}
con.Close();
}
}
return val;
}
Error is in this statement in WebMethod:
r.Photo = Convert.ToBase64String(p);
After changing JQuery hosted file to newer version,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
Error disappeared!
Related
i create a form where i upload picture into database in asp.net core mvc using ado.net.i face an issue that when i select picture it selects the picture but if i do one more time instead of add more picture it replace that picture which i select first help me to that thing in which i add further more picture. i create a list in which i upload the picture.Here is my code.
My Controller:
public IActionResult aprent([Bind] RentModel ar )
{
try
{
if (ModelState.IsValid)
{
if(ar.imge1 != null && ar.imge1.Count>0)
{
string folder = "image/";
foreach (IFormFile imge in ar.imge1)
{
folder += Guid.NewGuid().ToString() + "_" + imge.FileName;
ar.pic1 = "/" + folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
imge.CopyTo(new FileStream(serverFolder, FileMode.Create));
}
}
string res = DB.Saverecord(ar);
string pics = DB.imagedb(ar);
TempData["msg"] = res;
}
}
catch (Exception ex)
{
TempData["msg"] = ex.Message;
}
return View();
}
My Model:
public string? pic1 { get; set; }
public IFormFileCollection imge1 { get; set; }
My View:
<div class="row">
<input type="file" name="imge1" id="file" asp-for="imge1" class="hidden" multiple>
<button type="button" class="btn btn-primary" id="filebutton"><span id="filetext">Select File</span></button>
<div id="preview"></div>
</div>
<div id="image_preview"></div>
<script>
$(document).ready(function () {
$('#filebutton').click(function () {
$('#file').click();
});
$('#file').change(function () {
var name = $(this).val().split('\\').pop();
var file = $(this)[0].files;
if (name != '') {
if (file.length >= 2) {
$('#filetext').html(file.length + ' files ready to upload');
}
else {
$('#filetext').html(name);
}
}
});
$('#file').on("change", previewImages);
});
function previewImages() {
var $preview = $('#preview').empty();
if (this.files) $.each(this.files, readAndPreview);
function readAndPreview(i, file) {
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
} // else...
var reader = new FileReader();
$(reader).on("load", function () {
$preview.append($("<img>", { src: this.result, height: 80, }));
});
reader.readAsDataURL(file);
}
}
</script>
Do you want to choose more pictures at one time ?
Something like below? Hold down the Shift key when you choose pictures.
Update
if i select picture and after that i hit the choose button one more
time it select further more picture but not replace the previous
selected picture
i have also other data also i have same model in which my data exist
when i post form
You can try to use jQuery FilePond.
Below is a work demo, you can refer to it.
TestController:
public class TestController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(Testmodel testmodel,IFormFile[] photos)
{
return View();
}
}
Testmodel:
public class Testmodel
{
public string Name { get; set; }
public IList<IFormFile> photos { get; set; }
}
Index view:
#model Testmodel
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>
<script src="https://unpkg.com/jquery-filepond/filepond.jquery.js"></script>
<link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet"/>
<script src="https://unpkg.com/filepond/dist/filepond.js"></script>
<form id="uploadform" enctype="multipart/form-data">
<input type="text" asp-for="Name" />
<input type="file" class="filepond"asp-for="photos">
<button type="submit" class="uploadbtn">Upload Document</button>
</form>
<script>
$(document).ready(function(e){
pond = FilePond.create(
document.querySelector('.filepond'), {
allowMultiple: true,
instantUpload: false,
allowProcess: false
});
$("#uploadform").submit(function (e) {
e.preventDefault();
var formdata = new FormData(this);
// append FilePond files into the form data
pondFiles = pond.getFiles();
for (var i = 0; i < pondFiles.length; i++) {
// append the blob file
formdata.append('photos', pondFiles[i].file);
}
$.ajax({
url: "/test/Index",
data: formdata,
processData: false,
contentType: false,
method:"post"
});
})
});
</script>
result:
so I'm currently working on a forum-like project that involves users to be able to submit a post to a database and then for the post title to be displayed on a datatable. The hyperlink of title will re-direct the user to the postDisplay page based from the postId that is submitted through the url.
The project is an asp.net web-form that uses Entity Framework.
The following code is the Post.cs Class
public class Post
{
//The post ID
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int postId { get; set; }
// Foreign key to customer
public string Id { get; set; }
public string postTitle { get; set; }
public string postBody { get; set; }
public string postDepartment { get; set; }
public string postCategory { get; set; }
public bool postAnonymous { get; set; }
public int postLikes { get; set; }
public int postDislikes { get; set; }
public DateTime postDate { get; set; }
}
The code below is responsible for submitting the post to the db
protected void AddPost(object sender, EventArgs e)
{
ApplicationUserManager _userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
ApplicationUser user = _userManager.FindByName<ApplicationUser, string>(HttpContext.Current.User.Identity.Name);
var department = "";
using (var _dbContext = new ApplicationDbContext())
{
department = _dbContext.Departments.FirstOrDefault(c => c.deptId == user.deptId).deptName;
}
Post newPost = new Post()
{
postTitle = inputTitle.Text,
postBody = inputBody.Text,
postCategory = inputCategory.SelectedValue,
postAnonymous = Convert.ToBoolean(Int32.Parse(inputAnonymous.SelectedValue)),
Id = user.Id,
postDepartment = department,
postDate = DateTime.Now,
};
using (var _dbContext = new ApplicationDbContext())
{
_dbContext.Posts.Add(newPost);
_dbContext.SaveChanges();
}
//Display success message and clear the form.
string message = "Your suggestion has been submitted successfully!";
string script = "window.onload = function(){ alert('";
script += message;
script += "');";
script += "window.location = '";
script += Request.Url.AbsoluteUri;
script += "'; }";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
}
The code below is reponsible for creating the DataTable that views the post titles while hyperlinking the postId to the postDisplay Page
<div class="jumbotron">
<table class="display" id="postsTable">
<thead>
<tr>
<th>Title</th>
<th>Category</th>
<th>Date</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<br />
</div>
<asp:HiddenField id="deptName" runat="server"/>
<script type="text/javascript">
$(document).ready(function () {
$('#postsTable') .DataTable({
pageLength: "5",
ajax: {
url: "/api/posts/GetDatatables",
type: "GET",
dataType: "json",
dataSrc: ""
},
columns: [
{
render: function (data, type, row, meta) {
return '' + row.postTitle+'';
}
},
{data: "postCategory"},
{data: "postDate"},
]
});
});
</script>
Now for the final part where the error seems to stumble, the postDisplay page starts with
protected void Page_Load(object sender, EventArgs e)
{
int postId = int.Parse(Request.QueryString["postId"]);
}
According to the debugger, the postId is requested correctly and is parsed to an int, but when the value is then displayed as int postId, it doesn't actually carry the number with it in the url?
<-------------------------EDIT-------------------------->
The following error is displayed from the line of code above
"Input string was not in a correct format."
Any suggestions would be appreciated.
I am passing the value of doctype variable from my c# code to javascript.
Now I am unable to find any file based on the inputs.
Does the naming convention has to be exact?
Edit: Added current version with DocType hardcoded in onclick javascript page.
Variable:
DOC_TYPE in ascx.cs
DocType in ascx
AllGroup_UserControl.ascx.cs:
public partial class AllGroup_UserControl : UserControl
{
ProductProvider provider = new ProductProvider();
TBL_USER_PROFILEProvider uprovider = new TBL_USER_PROFILEProvider();
DocumentProvider dprovider = new DocumentProvider();
int DOC_TYPE;
// Document Types
const int G1_DOC_TYPE = 1;
const int G2_DOC_TYPE = 2;
const int G3_DOC_TYPE = 3;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string userName = SPContext.Current.Web.CurrentUser.Name;
TBL_USER_PROFILE p = uprovider.GetUser(userName);
if (p != null)
{
List<string> G1List = uprovider.GetAccessByModuleName(p.UserProfileID, "Group 1");
List<string> G2List = uprovider.GetAccessByModuleName(p.UserProfileID, "Group 2");
List<string> G3List = uprovider.GetAccessByModuleName(p.UserProfileID, "Group 3");
if (G1List.Count != 0)
{
DOC_TYPE = G1_DOC_TYPE;
}
else if (G2List.Count != 0)
{
DOC_TYPE = G2_DOC_TYPE;
}
else if (G3List.Count != 0)
{
DOC_TYPE = G3_DOC_TYPE;
}
else
{
Response.Redirect("/SitePages/AccessDeny.aspx");
}
Page.DataBind();
}
}
}
public int DocType
{
get
{
return DOC_TYPE;
}
}
//rest of the code
AllGroup_UserControl.ascx:
<a href="#" runat="server" onclick="openDialog('/SitePages/FileDownload.aspx?DocType=<%# DocType %>&ItemNo=<%#Eval("StoreItemNo")%>&CustomerID=<%#Eval("CustomerID")%>')">
ADDED:
Working code with docType hardcoded:
Group1_UserControl.ascx.cs: (with doctype hardcoded)
public partial class Group1_UserControl : UserControl
{
ProductProvider provider = new ProductProvider();
TBL_USER_PROFILEProvider uprovider = TBL_USER_PROFILEProvider();
DocumentProvider dprovider = new DocumentProvider();
int docType = 100;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string userName = SPContext.Current.Web.CurrentUser.Name;
TBL_USER_PROFILE p = uprovider.GetUser(userName);
if (p != null)
{
List<string> alist = uprovider.GetAccessByModuleName(p.UserProfileID, "Group 1");
if (alist.Count == 0)
Response.Redirect("/SitePages/AccessDeny.aspx");
}
}
}
}
Group1_UserControl.ascx: (with doctype hardcoded)
<a href="#" onclick="openDialog('/SitePages/FileDownload.aspx?DocType=100&ItemNo=<%#Eval("StoreItemNo")%>&CustomerID=<%#Eval("CustomerID")%>')">
You will have to use AJAX for that. Then you can pass values from backend to JavaScript.
Below is an example,
Client Side Script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "CS.aspx/YourFunctionHere",
data: '{name: "' + DocType + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
The Web Method
[System.Web.Services.WebMethod]
public static string YourFunctionHere(string name)
{
return "return value here";
}
I am working on a MVC web application and i am stuck on the following problem.
I have checkbox generated dynamically from my database, however i don't know how to get the value
of the selected one and stored that value in database.
Any Ideas?
Here is the code to retrieve a value from database,
public ActionResult GetAllProductsJson()
{
InventoryProductsRepository ir = new InventoryProductsRepository();
JsonResult jr = new JsonResult();
jr.Data = ir.GetAllProductsName();
jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jr;
}
and here is my javascript file
$(document).ready(function () {
var manageProduct = $("#manageProduct");
var tbody = $("#dataTable1").children("tbody");
var selectedProductName;
var currentSelectedProduct;
$.getJSON("/Client/Client/GetAllProductsJson", function (data) {
var tableData = "";
allProductInventoryJsonData = data; //To access from another function outside
$.each(data, function (key, value) {
var input = $("<input>");
input.attr("type", "checkbox");
input.attr("checked");
input.attr("value", value.ProductInventoryId);
var newSpan = $("<span>").html(value.Name);
$("<label>").addClass("ckbox ckbox-primary").append(input).append(newSpan).appendTo(manageProduct);
})
tbody.append(tableData);
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("failed to load table data" + errorThrown);
});
now i want to store that selected value in database.
Is there any idea what should i need to do?
Try this.
var checkedValues = [],
checkedOnes = $("label.ckbox-primary").find("input['type=checkbox']:checked");
checkedOnes.each(function( index ) {
checkedValues.push(this.value);
});
On the event where you want to post it back to server. ( Most probably a button click ). Then make a $.ajax call to post it.
Models
public class Movies
{
public int ID { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
public class MyViewModel
{
public List<Movies> movies { get; set; }
}
Controller
public class DemoListController : Controller
{
public ActionResult Index()
{
var oVm = new MyViewModel
{
movies = new List<Movies>
{
new Movies {ID=1,Name="Test1",IsSelected=false},
new Movies {ID=2,Name="Test2",IsSelected=false},
new Movies {ID=3,Name="Test3",IsSelected=false},
new Movies {ID=4,Name="Test4",IsSelected=false},
new Movies {ID=5,Name="Test5",IsSelected=false}
},
};
return View(oVm);
}
public JsonResult GetList(int id)
{
var list = new List<Movies>
{
new Movies {ID=1,Name="Test1",IsSelected=false},
new Movies {ID=2,Name="Test2",IsSelected=false},
new Movies {ID=3,Name="Test3",IsSelected=false},
new Movies {ID=4,Name="Test4",IsSelected=false},
new Movies {ID=5,Name="Test5",IsSelected=false}
};
List<Movies> select = new List<Movies>();
select = list.Where(x => x.ID == id).ToList();
return new JsonResult { Data = select, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
View
Index.cshtml
#model JsonCheckbox.Models.MyViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<h2>Movies...</h2>
<table>
#for (int i = 0; i < Model.movies.Count; i++)
{
<tr>
<td>
#Html.HiddenFor(x => Model.movies[i].ID)
#Html.CheckBoxFor(x => Model.movies[i].IsSelected,new {#class="cbk",hd=Model.movies[i].ID })
#Html.DisplayFor(x => Model.movies[i].Name)
#Html.HiddenFor(x => Model.movies[i].Name)
</td>
</tr>
}
</table>
<textarea id="txt" style="width:400px;height:200px"></textarea>
</div>
</body>
</html>
#Scripts.Render("~/Scripts/jquery-1.10.2.min.js")
<script type="text/javascript">
$(document).ready(function () {
$(".cbk").change(function () {
var select = "";
$("input[type = 'checkbox']").each(function () {
var c = $(this).is(":checked");
if (c) {
var t = $(this).attr("hd");
$.ajax({
type: "Get",
url: '#Url.Action("GetList", "DemoList")',
data: { id: $(this).attr("hd") },
dataType: "json",
success: function (data) {
select += "Id:" + data[0].ID + ",Name:" + data[0].Name + "; \n";
$("#txt").val(select);
}
})
} else {
$("#txt").val(select)
}
})
})
})
</script>
I am working on simple application where i am hitting the Request.aspx page from default2.aspx using jquery ajax post method as you can see below:
js page:
$(document).ready(function () {
$("#login").click(function () {
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
type: "POST",
url: "Request.aspx?Login=True",
data: "{'username': '" + email + "','password': '" + password + "'}",
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var url = "http://google.com";
//$(location).attr('href', url);
}
});
});
});
Default.aspx:
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/LoginCode.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div class="container">
<div class="main" id="loginform">
<label>
Email :</label>
<input type="text" name="demail" id="email" />
<label>
Password :</label>
<input type="password" name="password" id="password" />
<input type="button" name="login" id="login" value="Login" />
</div>
</div>
</div>
</form>
</body>
Request.cs Page:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Login"] != null)
{
test();
};
}
private string test()
{
var response = new ResponseResult();
var javaScriptSerializer = new JavaScriptSerializer();
response.Status = -1;
response.ErrorMessage = "";
response.Action = "UserProjects";
response.Data = "The Username or password you entered is not valid";
return javaScriptSerializer.Serialize(response);
}
public class ResponseResult
{
public string Action { get; set; }
public int Status { get; set; }
public string ErrorMessage { get; set; }
public object Data { get; set; }
}
Problem:
In response NUll is coming but i am expected json. Please let me know where i am going wrong.
If you need more info i will try my best to provide.
Thanks in advance.
It is a good idea to use Restful Webservices or Web Method to call from AJAX.
But still you can do the following.
Use Response.Write() instead of returning string.
Use this code.
private void test()
{
var response = new ResponseResult();
var javaScriptSerializer = new JavaScriptSerializer();
response.Status = -1;
response.ErrorMessage = "";
response.Action = "UserProjects";
response.Data = "The Username or password you entered is not valid";
string result = javaScriptSerializer.Serialize(response);
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(result); //write json string to output
}