The Entity is not getting loaded in Easy Query builder in MVC Application - asp.net-mvc

I have added the Easy Query Builder in to my MVC project by using the demo application of Easy Query Builder and i have added the .css and .js file according to the demo project. while executing
the entity is not getting loaded and the constructor and the getModel() is not been invoked. The EQ.Client is undefined once the page is loaded
Here is my code.
EasyQuery.cshtml( view )
<script type="text/javascript">
window.easyQuerySettings = {
serviceUrl: "/EasyQuery",
modelName: "NWindSQL",
entitiesPanel: { showCheckboxes: true },
columnsPanel: {
allowAggrColumns: true,
attrElementFormat: "{entity} {attr}",
showColumnCaptions: true,
adjustEntitiesMenuHeight: false,
menuOptions: {
showSearchBoxAfter: 30,
activateOnMouseOver: true
}
},
queryPanel: {
showPoweredBy: false,
alwaysShowButtonsInPredicates: false,
adjustEntitiesMenuHeight: false,
menuOptions: {
showSearchBoxAfter: 20,
activateOnMouseOver: true
}
},
syncQueryOptions: {
sqlOptions: { SelectDistinct: true }
},
};
function getPrefix() {
var res = window.location.pathname;
if (res.charAt(res.length - 1) !== '/')
res = res + '/';
return res;
}
</script>
<div class="entities-panel-container">
<div id="EntitiesPanel"></div>
</div>
<div class="columns-panel-container">
<div id="ColumnsPanel"></div>
</div>
<div class="query-panel-container">
<div id="QueryPanel"></div>
</div>
<script type="text/javascript">
**$(function () {
var query = EQ.client.getQuery();
EQ.client.loadModel({ modelName: "Model1" });
});**
</script>
in the EasyQuerycontroller.cs
public class **EasyQueryController** : Controller
{
private EqServiceProviderDb eqService;
public **EasyQueryController()**
{
eqService = new EqServiceProviderDb();
eqService.SessionGetter = key => Session[key];
eqService.SessionSetter = (key, value) => Session[key] = value;
eqService.StoreQueryInSession = true;
eqService.Formats.SetDefaultFormats(FormatType.MsSqlServer);
eqService.Formats.UseSchema = false;
string dataPath = System.Web.HttpContext.Current.Server.MapPath("~/App_Data");
eqService.DataPath = dataPath;
eqService.Connection = new SqlConnection("Data Source=" + System.IO.Path.Combine(dataPath, "Northwind.sdf"));
}
[HttpPost]
public ActionResult GetModel(string modelName)
{
var model = eqService.GetModel(modelName);
return Json(model.SaveToDictionary());
}
...
}
should i need to change some code or include some other feature to fill the EQ.Client element.?

I don't see where you actually include EasyQuery scripts on your view page.
There must be something like the following markup at the end (before closing "body" tag) of your view page:
<script src="http://cdn.korzh.com/eq/3.6.0/eq.all.min.js" type="text/javascript"></script>
<script src="http://cdn.korzh.com/eq/3.6.0/eq.view.basic.js" type="text/javascript"></script>

Related

How to display image in html from function javascript? ASP.NET

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:

Validate input field on submit

Im tryinf to validate this input field when i click on Submit button. What happens is when I click on the submit button and the textbox is empty it alert thank you,however it should alert Please check your submission
Html
<div id="newTest">
<fieldset>
<div class="row">
<label>Last name:</label>
<input type="text" data-bind="value: lastName" />
</div>
</fieldset>
<fieldset>
<button type="button" data-bind='click: submit'>Submit</button>
</fieldset>
</div>
Javascript
<script src="~/Scripts/knockout-3.5.0.js"></script>
<script src="~/Scripts/knockout.validation.min.js"></script>
<script>
var viewModel = function () {
ko.validation.rules.pattern.message = 'Invalid.';
ko.validation.init({
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null
}, true);
var self = this;
self.lastName = ko.observable().extend({ required: true }),
self.submit = function () {
if (viewModel.errors().length === 0) {
alert('Thank you.');
}
else {
alert('Please check your submission.');
viewModel.errors.showAllMessages();
}
};
};
viewModel.errors = ko.validation.group(viewModel);
var viewModel2 = new viewModel();
ko.applyBindings(viewModel2, document.getElementById("newTest"));
</script>
Since you are initializing viewModel2 as new viewModel(), these two lines of code:
viewModel.errors = ko.validation.group(viewModel);
var viewModel2 = new viewModel();
should be:
var viewModel2 = new viewModel();
viewModel.errors = ko.validation.group(viewModel2);
It's also unclear to me why you wrote this the way you did. It could be simpler IMO. Here's an example (JSFiddle: https://jsfiddle.net/vwuazfg0/):
ko.validation.rules.pattern.message = 'Invalid.';
ko.validation.init({
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null
}, true);
var viewModel = {
lastName : ko.observable().extend({ required: true }),
submit : function () {
if (viewModel.errors().length === 0) {
alert('Thank you.');
}
else {
alert('Please check your submission.');
viewModel.errors.showAllMessages();
}
}
};
viewModel.errors = ko.validation.group(viewModel);
ko.applyBindings(viewModel, document.getElementById("newTest"));

jquery tabs inside modal popup using MVChelper class

I am using a MVC helper class to display modal popup . my requirement is to show tabs inside this modal popup... here is what is did
My helper class
public static MvcHtmlString DialogROFormLink(this HtmlHelper htmlHelper, string linkText, string dialogContentUrl,
string dialogTitle, string updateTargetId, string updateUrl, string l_intHeight, string l_intWidth, string l_strFrmLinkPost )
{
TagBuilder builder = new TagBuilder("a");
builder.SetInnerText(linkText);
builder.Attributes.Add("href", dialogContentUrl);
builder.Attributes.Add("data-dialog-title", dialogTitle);
builder.Attributes.Add("data-update-target-id", updateTargetId);
builder.Attributes.Add("data-update-url", updateUrl);
builder.Attributes.Add("data-dialog-height", l_intHeight );
builder.Attributes.Add("data-dialog-width", l_intWidth );
builder.Attributes.Add("data-dialog-frmLink", l_strFrmLinkPost);
// Add a css class named dialogLink that will be
// used to identify the anchor tag and to wire up
// the jQuery functions
builder.AddCssClass("ROdialogLink");
return new MvcHtmlString(builder.ToString());
}
The JS file
$(function () {
// Don't allow browser caching of forms
$.ajaxSetup({ cache: false });
// Wire up the click event of any current or future dialog links
$('.ROdialogLink').live('click', function () {
var element = $(this);
// Retrieve values from the HTML5 data attributes of the link
var dialogTitle = element.attr('data-dialog-title');
var updateTargetId = '#' + element.attr('data-update-target-id');
var updateUrl = element.attr('data-update-url') + "?id=" + Math.floor(Math.random() * 1000);
// Generate a unique id for the dialog div
var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000)
var dialogDiv = "<div id='" + dialogId + "'></div>";
var lheight = element.attr('data-dialog-height');
var lwidth = element.attr('data-dialog-width');
var l_frmPost = element.attr('data-dialog-frmLink');
// Load the form into the dialog div
$(dialogDiv).load(this.href, function () {
$(this).dialog(
{
modal: true,
resizable: false,
width: lwidth,
height: lheight,
title: dialogTitle,
cache: false,
type: 'get',
buttons:
{
"Save": function () {
// Manually submit the form
var form = $('form', this);
$(form).submit();
},
"Cancel": function ()
{ $(this).dialog('destroy'); }
},
show: {
effect: "blind",
duration: 200
},
hide: {
effect: "blind",
duration: 200
}
})
// Enable client side validation
$.validator.unobtrusive.parse(this);
// Setup the ajax submit logic
wireUpForm(this, updateTargetId, updateUrl, l_frmPost);
});
return false;
});
});
function wireUpForm(dialog, updateTargetId, updateUrl, l_frmPost) {
$('form', dialog).submit(function () {
// Do not submit if the form
// does not pass client side validation
if (!$(this).valid())
return false;
$(dialog).dialog('close');
// Client side validation passed, submit the form
// using the jQuery.ajax form
return false;
});
}
Here is my view in which I have added the tabs script
<script>
$(function () {
$("CalendarTabs").tabs();
});
</script>
#using (Html.BeginForm())
{
<div id="CalendarTabs">
<ul>
<li>Estimate</li>
<li>Address/Phone/Insurance</li>
</ul>
<div id="CalTab-1">
</div>
<div id="CalTab-2">
</div>
</div>
}
I tried to show modal popup without using helper class to show popup including tabs and works fine. But fails in this case.
Please Help me! Thanks

Auto-complete doesn't work as expected

I tried to implement this in MVC 5 with jquery ui 1.10.2
#{
ViewBag.Title = "Home Page";
Layout = null;
}
<p>
Enter country name #Html.TextBox("Country")
<input type="submit" id="GetCustomers" value="Submit" />
</p>
<span id="rData"></span>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
#Styles.Render("~/Content/themes/base/css")
<script type="text/javascript">
$(document).ready(function () {
$("#Country").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/AutoCompleteCountry",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function(data) {
response($.map(data, function(item) {
return { label: item.Country, value: item.Country };
}));
}
});
}
});
})
</script>
the server side is
...
[HttpPost]
public JsonResult AutoCompleteCountry(string term)
{
// just something to return..
var list = new List<string>() { "option1", "option2", "option3"};
var result = (from r in list
select r);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
I have two issues
1. it open up drop down autocomplete with 3 dots but without the actual strings.
2. It has this annoying message of "3 results were found" - I'd like to eliminate it..
DO you have any idea how to face those two issues or neater way to implement it in MVC5?
The 3 bullet points and "3 results were found" is because you are missing the jQuery UI css file. That file will format a drop down that will look a lot better. You can customize how the dropdown looks with additional css.
Also, you are seeing 3 empty results because your JS is referencing item.Country ...
return { label: item.Country, value: item.Country };
But your server code is just sending 3 strings.
new List<string>() { "option1", "option2", "option3"};
To fix, change your JS to just reference the item (the string) ...
return { label: item, value: item};
OR, change your server code to send more complex objects
new List<Object>() { new { Country = "option1" }, new { Country = "option2" }, new { Country = "option3" } };
use return data in place of return { label: item.Country, value: item.Country };

Method not being triggered from razor view

I am using ASP.NET MVC 3 with the razor view engine.
I have the following method in my NewsController:
public JsonResult GetAllNews()
{
var items = newsService.FindAll();
var jsonResult = Json(items);
return jsonResult;
}
In my view I want to try and call this method to populate my YUI datatable. I put a breakpoint on the first line of this method but the breakpoint is not hit. Here is my code in the view to call this method:
var newsDataSource = YAHOO.util.DataSource('#Url.Action("GetAllNews");');
I even tried:
var newsDataSource = YAHOO.util.DataSource("/News/GetAllNews/");
Both don't seem to work.
Here is my datatable code:
<div id="grdNews"></div>
<script type="text/javascript">
// News grid
var newsColumnDefs = [
{ key: "id", label: "Identifier" },
{ key: "title", label: "Title" },
{ key: "body", label: "Body" }
];
//var newsDataSource = YAHOO.util.DataSource('#Url.Action("GetAllNews");');
var newsDataSource = YAHOO.util.DataSource("/News/GetAllNews/");
newsDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
newsDataSource.responseSchema = {
fields: [
{ key: "id" },
{ key: "title" },
{ key: "body" }
]
};
var myDataTable = new YAHOO.widget.DataTable("grdNews", newsColumnDefs, newsDataSource);
</script>
What am I doing wrong?
Don't forget to make this method return JSON for GET requests as well:
public JsonResult GetAllNews()
{
var items = newsService.FindAll();
return Json(items, JsonRequestBehavior.AllowGet);
}
Also setting a datasource doesn't mean that it will invoke the method. Maybe there's some other part of your code that's problematic. Install FireBug and see if an AJAX request is sent.
UPDATE:
Now that the question has been clarified and you are talking about YUI datatable, here's a full working example:
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult GetAllNews()
{
var news = new[]
{
new { id = 1, title = "title 1", body = "body 1" },
new { id = 2, title = "title 2", body = "body 2" },
new { id = 3, title = "title 3", body = "body 3" },
};
return Json(new
{
Result = news
}, JsonRequestBehavior.AllowGet);
}
}
View (~/Views/Home/Index.cshtml):
#{
ViewBag.Title = "Home Page";
}
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.2r1/build/fonts/fonts-min.css" />
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.2r1/build/datatable/assets/skins/sam/datatable.css" />
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/connection/connection-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/json/json-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/element/element-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/datasource/datasource-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/datatable/datatable-min.js"></script>
<script type="text/javascript">
var newsColumnDefs = [
{ key: "id", label: "Identifier" },
{ key: "title", label: "Title" },
{ key: "body", label: "Body" }
];
var newsDataSource = new YAHOO.util.DataSource('#Url.Action("GetAllNews")');
newsDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
newsDataSource.responseSchema = {
resultsList: 'Result',
fields: [ "id", "title", "body" ]
};
var myDataTable = new YAHOO.widget.DataTable("grdNews", newsColumnDefs, newsDataSource);
</script>
<div id="grdNews"></div>

Resources