MVC - display image from sqlite db - c#

how can i export an image from DB - Sqlite and display this image in the view?
im using angular code, and the images byte stored now in x.img var.
i want to display the image in img tag.
i tried few ways...
please your help.
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<link href="~/Content/productmenuStyle.css" rel="stylesheet" />
<script src="~/Scripts/angular.js"></script>
<script type="text/javascript">
var app = angular.module("myCode", []);
app.controller("CodeController", function ($scope, $http) {
$scope.Table = false;
$scope.showProduct = function (num) {
$scope.number = num;
$scope.getProduct(num);
}
$scope.getProduct = function (num) {
var list = $http({
method: 'post',
url: 'getProductjson',
params: {
prClass: num
}
});
list.then(function (list) {
$scope.Products = list.data;
}, function () {
alert("Inavalid data !!!");
});
}
$scope.sendProduct = function (num) {
var list = $http({
method: 'post',
url: 'sendProduct',
params: {
pid: num,
}
});
list.then(function (list) {
alert("The Product Addad To The Cart");
}, function () {
alert("Inavalid data !!!");
});
}
});
</script>
</head>

Related

how to create charts in asp.net core

what i want to do is creating charts from excuted data from a query in asp.net core but i face problem in usnig [httppost] in the controller when i use it gives me error 405 and when i don't use it the json data appear in the view and below are my codes.
Hello, what i want to do is creating charts from excuted data from a query in asp.net core but i face problem in usnig [httppost] in the controller when i use it gives me error 405 and when i don't use it the json data appear in the view and below are my codes.
public JsonResult Index()
{
string query = "select UserId, count(ServiceOrderNumber) as OrderNum from [dbo].[ServiceOrders] group by [UserId] order by count ([ServiceOrderNumber]) desc";
string constr = this._configuration.GetConnectionString("DefaultConnection");
List<object> chartData = new List<object>();
chartData.Add(new object[]
{
"UserId", "OrderNum"
});
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
chartData.Add(new object[]
{
sdr["UserId"], sdr["OrderNum"]
});
}
con.Close();
return Json(chartData);
}
and my view is
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "/Reports/Index/",
contentType: "application/json; charset=utf-8",
cache: false,
traditional: true,
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r);
//Pie
var options = {
title: 'USA City Distribution'
};
var chart = new google.visualization.PieChart($("#chart")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
<div id="chart" style="width: 500px; height: 400px;">
</div>
</body>
</html>
i face problem in usnig [httppost] in the controller when i use it
gives me error 405
The address bar of browser only support Get request.If you send the post request in browser address bar,it will get http 405 method not allowed error.
when i don't use it the json data appear in the
view and below are my codes.
If you remove HttpPost,it will be HttpGet by default.So when you enter the url in address bar,you will get the json string.
Also you may misunderstand ajax,ajax will be sent after your view has loaded.
You could check the document:
AJAX is a developer's dream, because you can:
Request data from a server - after the page has loaded
So,what you need do first is to send get request to backend to load the view and then it will hit the ajax you wrote. The whole principle you could check the gif below.
Here is a whole working demo:
Index.cshtml View in Views/Reports folder:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="~/lib/jquery/dist/jquery.min.js"></script> //be sure add jquery....
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "/Reports/Index/",
//url:"/Reports/GetJson/" //if you do not use route attribute in action
contentType: "application/json; charset=utf-8",
cache: false,
traditional: true,
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r);
//Pie
var options = {
title: 'USA City Distribution'
};
var chart = new google.visualization.PieChart($("#chart")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
<div id="chart" style="width: 500px; height: 400px;">
</div>
</body>
</html>
Controller:
public class ReportsController : Controller
{
//default is httpget
public ActionResult Index()
{
return View(); //it is used to load the view..
}
//if your request url is the same with get method,you could add route attribute.
//Because the controller could not have two same name method with the same parameter although they are used in different http request
[Route("Reports/Index")]
[HttpPost]
public JsonResult GetJson()
{
List<object> chartData = new List<object>();
chartData.Add(new object[]
{
"UserId", "OrderNum"
});
chartData.Add(new object[]
{
"1", 3
});
chartData.Add(new object[]
{
"2", 4
});
chartData.Add(new object[]
{
"3", 6
});
return Json(chartData);
}
}
Startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Result:

Processing multiline html textarea in c#

I have a textarea on my html page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#btnSquareNumbers").click(function () {
var Calculate = $("#txtString").val();
//Calculate = $("#txtString") //.Replace("<br/>", ",").TrimEnd(',')
$.ajax({
url: "/api/SquareNumbers/SquareNums/",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(Calculate),
success: function (result) {
$("#txtResult").val(result);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
$("#txtResult").val(err.Message)
}
});
});
});
</script>
</head>
<body>
<textarea id="txtString" cols=50 rows="15"></textarea><br>
<input type="button" value="Square All Numbers" id="btnSquareNumbers"><br>
<output type="text" id="txtResult" disabled />
</body>
</html>
It will accept a vertical list of numbers e.g.
2
5
8
13
I need to send this to the C# controller, square each number and display the results on the web page.
When I run the code, it truncates the numbers and gives 25813 squared!
I am new to this... any advice?
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace ReturnMultilineText.Controllers
{
public class SquareNumbersController : ApiController
{
[HttpPost]
public List<int> SquareNums([FromBody]string Calculate)
{
List<string> caseList = txtString.Split().ToList();
List<int> intList = caseList.ConvertAll(int.Parse);
List<int> ans = new List<int>();
for (var i = 0; i < intList.Count; i++)
{
ans.Add((intList[i] * intList[i]));
}
return ans;
}
}
}
Input:
1 2 3 4
2 3 4
Gives Output:
1,4,9,16,1,4,9
I am nearly there now.... Need to find the linefeed... does stringify remove it? and replace it with a space?
GOT THE SOLUTION... just needed to split by "\n"...
string[] textList = Calculate.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
Cheers for the help and advice.

How to call webservice in HTML page using JQuery?

i have WebService that get 2 string and return if they equals
WebService that in http://192.168.100.MyIP/HTML_SIMPLE_TEST/
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod(Description = "Validate the login credentials")]
public bool Validate(string UserName, string Password)
{
if (Password == "test" && UserName == "test")
return true;
else
return false;
}
}
and i have html page that call this WebService and need to return the Result
<html lang="en-US">
<head>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
var Surl = "http://localhost:3031/WS_HTML/Service1.asmx/Validate";
$(document).ready(function () {
$("input#submit").click(function (event) {
//var uid = document.getElementById("UserName").value;
//var pwd = document.getElementById("Password").value;
var uid = "test";
var pwd = "test";
var dataString = "{ 'UserName' : '" + uid + "', 'Password' : '" + pwd + "'}";
$.ajax({
ServiceCallID: 1,
url: Surl,
type: 'POST',
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
returnVal = result.d;
alert(returnVal);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
returnVal = '';
}
});
});
});
</script>
</head>
<body >
<form method=post runat="server">
<input type="submit" />Connet to my WS
</form>
</body>
</html>
this what i get:
and i try this, still same problem....
<script>
function XX() {
alert("in");
$.post('http://localhost/WS_HTML/Service1.asmx/Validate', { username: 'test', password: 'test' }, function (response) {
response; // Here is response
alert(response);
});
}
</script>
</head>
<body >
<form method=post runat="server">
<input type="submit" onclick="XX();" />Connet to my WS2
</form>
</body>
</html>
i try with $.get - and same.... Nothing happens....
from the browser its work. if i write this: localhost/WS_HTML/Service1.asmx i see my WS,
but if i write this: localhost/WS_HTML/Service1.asmx/Validate i see error on browser =>
Request format is unrecognized for URL unexpectedly ending in '/Validate'.
I swear to God that for several days I break my head and can not figure out why it does not work
):
thanks,
You not forced to use jQuery for make Ajax request. You can use standard javascript (it's more efficient, and you have not to load library for that...)
Also, you don't have to create an click event for submit your form, you can juste create an HTML structure and submit by an onclick attribute, is more efficient (less browser memory).
<!DOCTYPE html>
<html lang="en-US">
<head>
<script type="text/javascript">
var myUrl = "http://localhost:3031/WS_HTML/Service1.asmx/Validate";
function submitMyForm(){
// Define your datas
var uid = "test";
var pwd = "test";
var dataString = "{ 'UserName' : '" + uid + "', 'Password' : '" + pwd + "'}";
// Create and send the request
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
// Log with console.log() or alert if you want...
console.log('State of my request changed! ');
if (XMLHttpRequest.DONE === request.readyState) {
console.log(request.responseText);
}
}
request.open('POST', myUrl, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
}
</script>
</head>
<body>
<form>
<button onclick="submitMyForm()" >Connect to my WS</button>
</form>
</body>
</html>
I see you use a basic javascript alert() on your code, for the debug you can use console.log() (you can see the doc here).
For your question, I don't think the problem is your HTML/Javascript. jQuery method you've look right. HTML too.
I think you've a problem with your server, This not a client problem. It's a server error : you can see that with your HTTP status code (405 -> doumentation for this HTTP code here).
Have you right configured your server ? You can surrely found informations about 405 method not Allowed - ISS server on this website, on or the MSDN forum
Hope I help you.
Why not use $.post() ?
$.post('/your/service/url/', {username:'asd', password:'qwe'}, function(response){
response; // Here is response
});

Issues with binding controller methods in MVC

I am implementing a page which has two navigation hyperlinks: Previous and next.
First problem, Every time I click on a hyperlink, it calls the action for the first time. Second time onwards, it stops calling the action method on the controller. I know that browser caches the link. So i used the code OutputCache... but it still does not work.
Second problem is that the action method gets called twice on one click of the hyperlink .
Could someone tell me what am I missing here? It seems pretty simple for folks who have worked in Asp.net a lot. I have put down the code I am using. Please help.
Controller code:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*", Location = OutputCacheLocation.None)]
public string PreviousPage(int currentPage, int blogId){
List<Blog> blogs = db.Blogs.ToList();
List<Profile> profiles = db.Profiles.ToList();
var blog = blogs.FirstOrDefault(b => b.Id == blogId);
var detailsCount = blog.BlogDetails.Count();
if (currentPage == 0)
{
ViewBag.currentPage = Session["currentPage"]= currentPage;
}
else
{
ViewBag.currentPage =Session["currentPage"]= currentPage - 1;
}
ViewBag.blogId = Session["blogId"] = blogId;
ViewBag.blogTitle = Session["blogTitle"] = blog.Title;
if (blog.BlogDetails.Any())
{
return blog.BlogDetails[ViewBag.currentPage].BlogPage;
}
else {
return " ";
}
}
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*", Location = OutputCacheLocation.None)]
public string NextPage(int currentPage, int blogId){
List<Blog> blogs = db.Blogs.ToList();
List<Profile> profiles = db.Profiles.ToList();
var blog = blogs.FirstOrDefault(b => b.Id == blogId);
var detailsCount = blog.BlogDetails.Count();
if (currentPage == detailsCount - 1)
{
ViewBag.currentPage = Session["currentPage"] = currentPage;
}
else
{
ViewBag.currentPage = Session["currentPage"] = currentPage + 1;
}
ViewBag.blogId = blogId;
Session["blogTitle"] = blog.Title;
if (blog.BlogDetails.Any())
{
return blog.BlogDetails[ViewBag.currentPage].BlogPage;
}
else
{
return " ";
}
}
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public JsonResult UpdateTitleServer(){
var title = Session["blogTitle"];
int blogId = (int)Session["blogId"];
var currentPage = (int)Session["currentPage"];
var result = new {
Title = title.ToString(),
BlogPrevLink = string.Format("/BloggerHome/PreviousPage?currentPage={0}&blogId={1}",currentPage,blogId),
BlogNextLink = string.Format("/BloggerHome/NextPage?currentPage={0}&blogId={1}",currentPage,blogId)
};
return Json(result,JsonRequestBehavior.AllowGet);
}
View code:
#Ajax.ActionLink("<----", "PreviousPage","BloggerHome", new { currentPage = ViewBag.currentPage, blogId = ViewBag.blogId }, new AjaxOptions() {HttpMethod="Post", OnComplete="UpdateTitleClient", UpdateTargetId = "contentPanel" }, new {Id="PrevPage"})
#Ajax.ActionLink("---->", "NextPage","BloggerHome", new { currentPage = ViewBag.currentPage, blogId = ViewBag.blogId }, new AjaxOptions() {HttpMethod="Post",OnComplete="UpdateTitleClient",UpdateTargetId="contentPanel" },new {Id="NextPage"});
JavaScript method:
function UpdateTitleClient() {
$.getJSON("BloggerHome/UpdateTitleServer", function (data) {
$("#blogTitle").html(data.Title);
$("#PrevPage").attr("href", data.BlogPrevLink);
$("#NextPage").attr("href", data.BlogNextLink);
});
}
Remember that getJSON() is an async method so the sequence of events may not be very predictable if you are stepping through the code using a debugger.
getJSON() doesnt have a async:false setting so just use ajax instead set async to false and dataType to json. Something like below:
$.ajax({
dataType: "json",
url: yoururl,
async: false,
data: data,
success: function (data) {
$("#blogTitle").html(data.Title);
$("#PrevPage").attr("href", data.BlogPrevLink);
$("#NextPage").attr("href", data.BlogNextLink);
}
});
The line #Scripts.Render("~/bundles/jqueryval") , Jquery validation script inclusion is causing the controller methods to call twice. I am not sure why this is causing the problem .Once this line was removed, it calls the controller method once only.
This is how my script header looked like before
<head>
<meta charset="utf-8" />
<title>Test</title>
<meta name="viewport" content="width=device-width" />
<script type="text/javascript" src="~/Scripts/jquery-1.8.2.min.js" ></script>
<script type="text/javascript" src="~/Scripts/jquery-ui-1.8.24.js" ></script>
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
**#Scripts.Render("~/bundles/jqueryval") // Removed this line**
</head>
This issue is due to jquery references being added twice.
First reference was :
**<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.min.js"</script>**
Second Reference was due to the line :
#Scripts.Render("~/bundles/jqueryval")
The above line adds three scripts to the web page
**<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>**
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
The two highlighted script tags are duplicates which caused the controller methods to be called twice . I removed one of them and it works fine now.

Getting an error doing serverside XML processing

So I have an aspx page that servers XML + XSL to a client and does a client-side transform which works fine.
I am trying to detect the client and if they don't support client side transformation I am doing it serverside. I am interrupting the render processor the aspx page that would return XML and I am getting it's output, combining it with the output from the XSL page and serving it out. This output however is not well formed. I get
XML Parsing Error: mismatched tag. Expected: </link>.
Location: http://oohrl.com/dashboard.aspx
Line Number 36, Column 20: </script></head>
-------------------^
In the client side generated output, which works fine, I get for instance
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="./css/dboard.css"/>
<link rel="stylesheet" type="text/css" href="./css/dboardmenu.css"/>
<script type="text/javascript" src="./js/simpletabs.js"/>
<link href="../css/simpletabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"/>
<script type="text/javascript">
$(document).ready(function () {
$("#BlogSelectList li a").live("click", function () {
var str = ($(this).attr("href")).slice(1, 37)
$.ajax({
contentType: "application/json; charset=utf-8",
url: '../ws/WebServices.asmx/SetActiveBlog',
data: '{ActiveBlogID: "' + str + '"}',
dataType: 'json',
type: "post",
success: function (j) {
window.location.href = 'dashboard.aspx'
}
});
});
})
function showlayer(layer) {
var myLayer = document.getElementById(layer);
if (myLayer.style.display == "none" || myLayer.style.display == "") {
myLayer.style.display = "block";
}
else {
myLayer.style.display = "none";
}
}
</script></head>
If I generate it server side I get
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-16">
<link rel="stylesheet" type="text/css" href="./css/dboard.css">
<link rel="stylesheet" type="text/css" href="./css/dboardmenu.css">
<script type="text/javascript" src="./js/simpletabs.js"></script>
<link href="../css/simpletabs.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#BlogSelectList li a").live("click", function () {
var str = ($(this).attr("href")).slice(1, 37)
$.ajax({
contentType: "application/json; charset=utf-8",
url: '../ws/WebServices.asmx/SetActiveBlog',
data: '{ActiveBlogID: "' + str + '"}',
dataType: 'json',
type: "post",
success: function (j) {
window.location.href = 'dashboard.aspx'
}
});
});
})
function showlayer(layer) {
var myLayer = document.getElementById(layer);
if (myLayer.style.display == "none" || myLayer.style.display == "") {
myLayer.style.display = "block";
}
else {
myLayer.style.display = "none";
}
}
</script></head>
Which gives me the error. Of course I notice the difference in the <link/> vs <link> tag but I have no idea why the server side processing engine give me different results or how to fix it?
Here is the code I use to generate the XHTML on the server
protected override void Render(HtmlTextWriter writer)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hWriter = new HtmlTextWriter(sw);
base.Render(hWriter);
// *** store to a string
string XMLOutput = sb.ToString();
// *** Write it back to the server
if (!Request.Browser.IsBrowser("IE"))
{
writer.Write(XMLOutput);
}
else
{
StringWriter XSLsw = new StringWriter();
HttpContext.Current.Server.Execute("DashboardXSL.aspx", XSLsw);
string output = String.Empty;
using (StringReader srt = new StringReader(XSLsw.ToString())) // xslInput is a string that contains xsl
using (StringReader sri = new StringReader(XMLOutput)) // xmlInput is a string that contains xml
{
using (XmlReader xrt = XmlReader.Create(srt))
using (XmlReader xri = XmlReader.Create(sri))
{
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xrt);
using (StringWriter _sw = new StringWriter())
using (XmlWriter xwo = XmlWriter.Create(_sw, xslt.OutputSettings)) // use OutputSettings of xsl, so it can be output as HTML
{
xslt.Transform(xri, xwo);
output = _sw.ToString();
}
}
}
writer.Write(output);
Response.Flush();
Response.End();
}
Because the root element of your output document is <html>, the processor chooses HTML as the default format. To create a well-formed XHTML document instead, make sure your XSLT contains the following as a child of the root <xsl:stylesheet> or <xsl:transform> element:
<xsl:output method="xml" omit-xml-declaration="yes" />
I had to set the content type on the xsl sheet to text/html which fixed all problems.
Note this change is ONLY used when transforming server side. When sending it to the client for a client transformation it is not changed to text/html

Categories