How to display image in html from function javascript? ASP.NET - asp.net-mvc

halo guys can you help me to display image. How to display image in html from function javascript? ASP.NET
this is my html:
<div class="col-md-4">
<img id="DisplayImage" class="img-responsive thumbnail" width="200" height="200" />
</div>
javascript here =
var DisplayImage = function () {
var file = $("#SelectImage").get(0).files;
var data = new FormData;
data.append("ImageFile", file[0]);
$.ajax({
type: "GET",
url: '/Home/DisplayImage',
data: data,
contentType: false,
processData: false,
success: function (imgID) {
$("#DisplayImage").show();
$("#img_cgv").attr("src", "/UploadImage/" + imgID);
console.log(imgID);
}
})
}
my controller :
[HttpGet]
public ActionResult DisplayImage(int imgid)
{
Models.eCoalDataContext db = new eCoalDataContext();
var img = db.TBL_M_IMAGEs.SingleOrDefault(x => x.ID == imgid);
/*return File("image/jpg");*/
return File(img.IMAGE_TITLE, "image/jpg");
}

I don't have the code about your files, so in my demo I remove it. Below is a work demo to display image in html from function javascript, you can refer to it, hope it can help you.
Besides, in I have e.PNG in UploadImage folder like:
In Controller:
public class DisplayController : Controller
{
public IActionResult Index()
{
return View();
}
public ActionResult DisplayImage(int imgid)
{
imgid = 1;
var Images = new List<Images>()
{ new Images(){ID=1,IMAGE_TITLE="e.PNG"},
new Images(){ID=2,IMAGE_TITLE="flower.PNG"}
};
var img = Images.SingleOrDefault(x => x.Id == imgid);
return Json(img.IMAGE_TITLE);
}
}
Index view:
<input onclick="getA1Rates()" value="Click" type="button"/>
<div class="col-md-4">
<img id="img_cgv" class="img-responsive thumbnail" width="200" height="200" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
function getA1Rates() {
$.ajax({
type: "GET",
url: '/Display/DisplayImage',
contentType: false,
processData: false,
success: function (imgID) {
$("#img_cgv").attr("src", "/UploadImage/" + imgID);
console.log(imgID);
}
})
}
</script>
result:

Related

Select2 initSelection element Val

I am using the select2 control on my web aplciation. In the initSelection I am passing the element.val() to a controller but it is null. How would I set element.val() that i want pass to the Url.Action. Is element.val() the correct object that I should be using when I am using a div?
I see the value in Chrome
debugger
view
<div id="guideline-container" style="#(Model.Type == "Guideline" ? "display:block" : "display:none")">
<form id="guideline-form" class="form-horizontal">
<div class="form-group">
<label for="guidelineName" class="col-sm-2 control-label">Guideline</label>
<div class="col-sm-10">
<div id="guidelineName">
#{ Html.RenderAction("Index", "GuidelinesPicklist", new { value = Model.GuidelineId, leaveOutAlgorithmItems = true, separateActiveItems = true }); }
</div>
<div class="guideline-not-selected field-validation-error" style="display: none;">
Guideline is required.
</div>
</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary modal-submit-btn">Add</button>
<button type="button" class="btn btn-default modal-close-btn" data-dismiss="modal">Close</button>
</div>
</form>
</div>
function
$(this).select2({
placeholder: "#Model.Settings.Placeholder",
//allowClear: true,
ajax: {
url: "#Url.Action("GetPicklistItems")",
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
data: function (params) {
return JSON.stringify({
query: params.term,
args: #Html.Raw(JsonConvert.SerializeObject(#Model.Settings != null ? #Model.Settings.AdditionalArguments : null))
});
},
processResults: function (data, page) {
console.log("processResults");
console.log(data);
var resultData = [];
if (isError(data)) {
showErrorMessage(getErrorMessage(data));
} else {
hideErrorMessage();
mapResultData(data.Result, resultData, 0);
}
return {
results: resultData
};
}
},
templateResult: format,
templateSelection: function(data) {
return data.text;
},
initSelection: function (element, callback) {
//console.log("initSelection");
//var id = $(element).val();
//console.log(id);
var guidelineId = "#Model.Value";
console.log("guidelineId");
console.log(guidelineId);
//console.log("params");
//console.log(params);
//console.log("element object Text");
//console.log(element.text);
debugger;
getAjax("#Url.Action("GetPicklistItem")" + "?value=" + guidelineId, function (result)
{
console.log("Ajax GetPicklistItem");
console.log(result);
debugger;
if (result.Result) {
var data = {};
$.extend(data, result.Result);
data.id = result.Result.Value;
data.text = result.Result.Text;
callback(data);
self.trigger("picklistChanged", data);
} else {
console.log(result);
debugger;
callback ({ id: null, text: "#Model.Settings.Placeholder" })
}
});
},
escapeMarkup: function(m) {
return m;
}
}).on('change', function () {
var data = self.select2('data');
self.trigger("picklistChanged", data);
});
You can get Select2 selected value or text by using the following approaches:
var selectedValue = $('#Employee').val();
var selectedText = $('#Employee :selected').text();
Alternatively you can simply listen to the select2:select event to get the selected item:
$("#Employee").on('select2:select', onSelect)
function onSelect(evt) {
console.log($(this).val());
}

Case Closed - Pass JSON data to Controller MVC

I want to pass this data from my view to save it via controller.
My view
<div>
<b>Title</b> <br />
<input type="text" id="title" /><br />
<b>Description</b> <br />
<input type="text" id="desc" /><br />
</div>
<button id="saveDetails">Save</button>
My js
$(document).ready(function () {
$(document).on("click", "#saveDetails", saveDetails);
$("#detailsPanel").hide();
});
var saveDetails = function () {
var dataPost = {
"Title": $("#title").val(),
"Description": $("#desc").val(),
"AssetId": $("#assetId").val()
}
$.ajax({
type: "POST",
async: false,
contentType: "application/json",
data: JSON.stringify(dataPost),
url: "/Media/Save"
}).done(function (state) {
if (state.Saved == true) {
displayStatusMessage("Saved Successfully");
$("#detailsPanel").hide();
mediaPlayer.initFunction("videoDisplayPane", state.StreamingUrl);
} else {
displayStatusMessage("Save Failed");
}
});
}
My Controller
[HttpPost]
public JsonResult Save(MediaElement mediaelement)
{
try
{
mediaelement.UserId = User.Identity.Name;
mediaelement.FileUrl = GetStreamingUrl(mediaelement.AssetId);
db.MediaElements.Add(mediaelement);
db.SaveChanges();
return Json(new { Saved = true, StreamingUrl = mediaelement.FileUrl });
}
catch (Exception ex)
{
return Json(new { Saved = false });
}
}
Its already post the data to my controller (i saw it via Fiddler), but it always return Json(new { Saved = false }).
Anything wrong with my code? Need help, please...
[Case Closed]
Okay, I found in my db, i have coloumn UploadDate which is not null. And I already declare the default value on my db with this -> getdate(). But it doesnt work when I inserted data from controller. So i add the value of UploadDate manually via Controller. Then Its Works:)
Thanks everybody :)
i think the problem is with the MediaElement model binding ...
but before, check the folowing :
you can try to remove the JSON type of your ajax.
your json format.
the dataPost var miss the ; end.
$(document).ready(function () {
$(document).on("click", "#saveDetails", saveDetails);
$("#detailsPanel").hide();
});
var saveDetails = function () {
var dataPost = {
Title: $("#title").val(),
Description: $("#desc").val(),
AssetId: $("#assetId").val()
};
$.ajax({
type: "POST",
async: false,
data: dataPost,
url: "/Media/Save"
}).done(function (state) {
if (state.Saved == true) {
displayStatusMessage("Saved Successfully");
$("#detailsPanel").hide();
mediaPlayer.initFunction("videoDisplayPane", state.StreamingUrl);
}
else {
displayStatusMessage("Saved Failed");
}
});
}

How can I preserve the form values when I use MVC with Knockout

I'm developing (for the first time) an MVC application using ajax call and knockout MVVM to fill 2 cascading dropdown lists.
The question is, How can I preserve the values I selected in the dropdown lists, when I post the web page?
The web page I'm developing makes calculations when is posted to the controller and the controller must return the calculated result. When the result is returned, the values of the form must be preserved.
a part of the View
#using (Html.BeginForm("Calculate", "Entypo", FormMethod.Post, new { role = "form" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(false)
<fieldset>
<legend>Printers</legend>
<div class="row">
<div class="form-group col-md-6">
<select id="printers" name="printers" class="form-control" data-bind="options: printers, optionsValue: 'ID', optionsText: 'BrandModelName', value: selectedPrinter, optionsCaption: 'Choose Printer...'"></select>
</div>
<div class="form-group col-md-6">
<select id="sheets" name="sheets" class="form-control" data-bind="options: sheets, optionsValue: 'ID', optionsText: 'Description', optionsCaption: 'Choose Sheet...', enable: sheets().length, value: sheet">
</select>
</div>
</div>
</fieldset>
<div class="row">
<div class="col-md-12" style="padding-bottom:10px;">
<input type="submit" value="Calculate" class="btn btn-primary" />
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/knockout-3.0.0.js"></script>
<script>
$(document).ready(function () {
// MVVM
viewModel = {
printer: ko.observable(),
printers: ko.observableArray(),
sheet: ko.observable(),
sheets:ko.observableArray(),
paper: ko.observable(),
papers: ko.observableArray(),
weight: ko.observable(),
weights: ko.observableArray(),
size: ko.observable(),
sizes: ko.observableArray(),
lamA: ko.observableArray(),
lamAvalue: ko.observable(),
lamB: ko.observableArray(),
lamBvalue: ko.observable(),
chkCut: ko.observable(false),
chkFold: ko.observable(false),
chkPick: ko.observable(false),
chkPerfore: ko.observable(false),
standardSize: ko.observable(),
x: ko.observable(),
y: ko.observable(),
bleed: ko.observable(2.5),
qty: ko.observable(1)
};
viewModel.standardSize.subscribe(function () {
var st = viewModel.standardSize();
var res = st.split("x");
viewModel.x(res[0]);
viewModel.y(res[1]);
});
$.ajax({
url: '/Entypo/getPrinters',
type: 'GET',
dataType: 'json',
data: {},
success: function (data) {
viewModel.printers(data);
}
});
viewModel.selectedPrinter = ko.dependentObservable({
read: viewModel.printer,
write: function (printer) {
this.printer(printer);
$.ajax({
url: '/Entypo/getSheets',
type: 'GET',
dataType: 'json',
data: { id: viewModel.selectedPrinter() },
success: function (data) {
viewModel.sheets(data);
}
});
},
owner: viewModel
});
$.ajax({
url: '/PaperSize/getPapers',
type: 'GET',
dataType: 'json',
data: {},
success: function (data) {
viewModel.papers(data);
}
});
viewModel.selectedPaper = ko.dependentObservable({
read: viewModel.paper,
write: function (paper) {
this.paper(paper);
$.ajax({
url: '/Entypo/getWeights',
type: 'GET',
dataType: 'json',
data: { id: viewModel.selectedPaper() },
success: function (data) {
viewModel.weights(data);
}
});
},
owner: viewModel
});
viewModel.selectedWeight = ko.dependentObservable({
read: viewModel.weight,
write: function (weight) {
this.weight(weight);
$.ajax({
url: '/Entypo/getSizes',
type: 'GET',
dataType: 'json',
data: { id: viewModel.selectedWeight() },
success: function (data) {
viewModel.sizes(data);
}
});
},
owner: viewModel
});
$.ajax({
url: '/Entypo/getLamination',
type: 'GET',
dataType: 'json',
data: {},
success: function (data) {
viewModel.lamA(data);
viewModel.lamB(data);
}
});
ko.applyBindings(viewModel);
});
</script>
The Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QVNet_v2.Models;
namespace QVNet_v2.Controllers
{
public class EntypoController : Controller
{
private QVNetEntities db = new QVNetEntities();
//
// Calc: /Entypo/
[HttpGet]
public ActionResult Calculate()
{
return View();
}
[HttpPost]
public ActionResult Calculate()
{
return View();
}
//GET PRINTERS
public JsonResult getPrinters()
{
var printers = db.Printers.Select(s => new { s.ID, s.BrandModelName }).OrderBy(s=>s.BrandModelName).ToList();
return Json(printers, JsonRequestBehavior.AllowGet);
}
//GET SHEETS USED FROM SELECTED PRINTER
public JsonResult getSheets(int id)
{
var sheets = db.Sheets.Select(s => new { s.ID, s.Description, s.PrinterID }).Where(s=>s.PrinterID ==id).OrderBy(s=>s.Description).ToList();
return Json(sheets, JsonRequestBehavior.AllowGet);
}
// GET PAPERS
public JsonResult getPapers()
{
var papers = db.Papers.Select(s => new { s.ID, s.Description }).OrderBy(s => s.Description).ToList();
return Json(papers, JsonRequestBehavior.AllowGet);
}
// GET WEIGHTS OF SELECTED PAPER
public JsonResult getWeights(int id)
{
var weights = db.PaperWeights.Select(s => new { s.ID, s.Weight, s.PaperID }).Where(s => s.PaperID == id).OrderBy(s => s.Weight).ToList();
return Json(weights, JsonRequestBehavior.AllowGet);
}
//GET SIZES OF SELECTED PAPER AND WEIGHT
public JsonResult getSizes(int id)
{
var sizes = db.PaperSizes.Select(s => new { s.ID, s.Description, s.PaperWeightID }).Where(s => s.PaperWeightID == id).OrderBy(s => s.Description).ToList();
return Json(sizes, JsonRequestBehavior.AllowGet);
}
//GET LAMINATION
public JsonResult getLamination()
{
var lam = db.SheetLaminations.Select(s => new { s.ID, s.Description }).OrderBy(s => s.Description).ToList();
return Json(lam, JsonRequestBehavior.AllowGet);
}
//Dispose db
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
When the user click the submit value, the controller must take the data from the form and return the results of a calculation while keeping intact the form fields.
Sorry for my English.
You have two possible ways.
Submit your form using ajax. You will keep your form
open thus all values will be unchanged. You can use #using
(Ajax.BeginForm) or create knockout method that will call $.ajax to save your data and
assing this method to submit button.
Second approach - make your form strongly typed. Create viewmodel
class that will hold all values needed to construct the form. In
your saving action (Calculate method annotated with [HttpPost])
you shoud recreate viewmodel based on actual form values and send it
back to the view.

Ajax call on separate js file

I can use ajax call on *.cshtml file as below.It's working properly.
$.ajax({
url: '#Url.Action("GetAllBooks", "Book")',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.Books(data); //Put the response in ObservableArray
}
});
But How can I call same method on seperate *.js file ?When I used above code it's not working?
CSHTML (I prefer the tag input):
#* without the attribute 'name' *#
<input type="hidden" value="#Url.Action("GetAllBooks", "Book")" id="UrlBookGetAllBooks" />
#* or *#
<div style="display:none;" data-url="#Url.Action("GetAllBooks", "Book")" id="UrlBookGetAllBooks"></div>
JS:
var url = $('#UrlBookGetAllBooks').val();
//or for tag div
var url = $('#UrlBookGetAllBooks').data('url');
$.ajax({
url: url,
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.Books(data); //Put the response in ObservableArray
}
});
HTML - Contains data- attributes
<div id="ExampleDiv"
data-url = "#Url.Action("Action", "Controller", new { area = "AreaName" })">
</div>
HTML - Option 2
<div id="ExampleDiv"
url-Val = "#Url.Action("Action", "Controller", new { area = "AreaName" })">
</div>
JQuery - Contains data- attributes
var Url_Value = $('#ExampleDiv').data('url');
JQuery - Option 2
var Url_Value = $('#ExampleDiv').attr('url-Val');
Ajax Call
$.ajax({
url: Url_Value,
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.Books(data); //Put the response in ObservableArray
}
});
For such solution, I recommends you to create a JavascriptController with a "JavascriptActionResult" or a new "JavascriptActionResult" on the BookController along with the view that outputs the desired javascript. That way you can write Javascript dynamically with razor and also have garantee that the Route Pattern behavior of your MVC will be followed. With all that set, the page would be:
<script type="text/javascript" src="#Url.Action("GetAllBooksJS","Book")"></script>
PS: There is not a native JavascriptActionResult in MVC, but you could extend the ActionResult to perform that or simple force a Content-Type in the classic ActionResult function.
Bellow is a working case that Ive made in MVC3.
Controller:
public class BookController : Controller
{
//
// GET: /Book/
public ActionResult Index()
{
return View();
}
public JsonResult GetAllBooks() {
return Json(new[] { new { name = "Book1" }, new { name = "Book2" } });
}
public ActionResult GetAllBooksJS()
{
Response.ContentType = "text/javascript";
return View();
}
}
Index View:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script type="text/javascript" src="#Url.Content("~/scripts/jquery-1.7.1.min.js")"> </script>
<script type="text/javascript" src="#Url.Action("GetAllBooksJS","Book")"></script>
</head>
<body>
<div>
<button>Get books ajax</button>
</div>
</body>
</html>
GetAllBooksJS View:
#{
Layout = null;
}
$(document).ready(function(){
$('button').on('click',function() {
GetBooksAjax();
});
});
function GetBooksAjax() {
$.ajax({
url: '#Url.Action("GetAllBooks","Book")',
type: 'POST',
dataType: 'json',
success: function(oJSON) {
$.each(oJSON,function(){
alert(this.name);
})
}
})
}
GetAllBooksJS View v2, In this second version the Javascript, as soon as it is loaded by the Index view, will engage the Ajax Call, I guess thats your case:
#{
Layout = null;
}
function GetBooksAjax() {
$.ajax({
url: '#Url.Action("GetAllBooks","Book")',
type: 'POST',
dataType: 'json',
success: function(oJSON) {
$.each(oJSON,function(){
alert(this.name);
})
}
})
}
GetBooksAjax();

Is not the way I want PartialViewResult

I try something.I apologize in advance for my english.
My Action code;
public PartialViewResult showProduct()
{
var query = db.Categories.Where((c) => c.CategoryID == 4);
return PartialView("_EditCategory",query);
}
My view code:
#using (Ajax.BeginForm(
"showProduct",
new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "result"
}))
{
<input type="submit" value="Get" />
}
<div id="result">
</div>
When i pushed the submit button ( which value is get) the results return but in another page like http://localhost:57616/Home/showProduct but i want return to result div in index page.
Any one can help me?
So, how I handled this myself was something like this:
$(document).ready(function () {
var options = {
target: "#mytargetdiv",
url: '#Url.Action("Edit", "IceCream")',
};
$("#editIceCreamForm").submit(function () {
$(this).ajaxSubmit(options);
return false;
}
// other stuff
});
in other places, where I wanted to do in-place editing of things I'd do something like this:
<input type="button" id="someid" value="Edit" data-someid="#Model.SomeId"/>
and then some ajax like so:
$(function () {
$("#someid".click(function () {
var theId = $(this).data('someid');
$.ajax({
type: "GET",
data: "id=" + theId,
url: '#Url.Action("Edit", "Something")',
dataType: "html",
success: function (result) {
$('#targetdiv').html(result);
}
});
});
});
So, if you're not interested in using jQuery and want to use the MS Ajax stuff, are you including the MicrosoftAjax.js and MicrosoftMvcAjax.js files on the page? If you don't have those, I believe what will happen is it just does the default (non-Ajax) submit.

Resources