I am very fresh to asp.net mvc and jQuery. After one day trying, I still don't know how to pop up a jQuery dialog using data from a action(return JsonResult) while user click a link.
Any suggest or guideline is appreciate.
Thanks!
Thx for Stuntz & RhinoDevX64 's reply, finally I work it out.
jQuery Code:
<script type="text/javascript">
$(function() {
$('.newsitem').click(function() {
var $thisLink = $(this);
$('#dialog').empty();
$.getJSON($thisLink.attr("href"), function(data) {
$('#dialog').html(data.content);
$("#dialog").dialog({
autoOpen: false,
title: data.title,
bgiframe: true,
modal: true,
height: 450,
width: 540,
buttons: {
'关闭': function() {
$(this).dialog('close');
}
}
});
$('#dialog').dialog('open');
});
return false;
});
});
</script>
ActionLink
<%= Html.ActionLink(item.Title, "GetByJs", "Article", new { id = item.ID }, new { #class = "newsitem" })%>
Action Code
public ActionResult GetByJs(Guid id) {
var item = Article.SingleOrDefault(a => a.ID == id && a.AtFront == true);
var jsonData = new {
title = item.Title, content = item.BodyContent
};
return new JsonResult {
Data = jsonData
};
}
var ph = $("#idOfPlaceHolderInPage");
ph.load(/Controller/SomeActionWhichReturnsPartialView, function() {
// this callback will be called after your partial view loaded into placeholder
ph.dialog({
// pass options here to customize dialog
});
});
1st use jQuery UI follow their documentation for including the css and js files.
<script src="../../Scripts/jquery-1.3.2.js" type="text/javascript" ></script>
<script src="../../Scripts/jquery-ui-1.7.1.custom.min.js" type="text/javascript"></script>
<link href="../../Content/jquery-ui-1.7.1.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function(){
$("#idOfModalPlaceholder").dialog({autoOpen: false, title:"MODAL TITLE"});
});
function OpenModalGetContent(){
$("#idOfModalPlaceHolder").load("/Controller/View");
$("#idOfModalPlaceHolder").dialog('open');
}
</script>
CLICK HERE FOR MODAL
2nd You should really just use a regular ActionResult and a Partial View (*.ascx), if you are just grabbing some content;
if you are calling data I presume you may be loading into an autocomplete which would be completely different than this scenario.
Related
I have successfully implemented autocomplete search option in my laravel project "book shop managing". Again from my homepage if I click on the name of a book then it would show the specific book. But how can I add link to my search result, so that if I click on a book from the result then it would take me to the page that contains the book details.
my index.blade.php
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#books" ).autocomplete({
source: 'auto_complete'
});
});
</script>
<div class="ui-widget">
<label for="books">Books: </label>
<input id="books">
</div>
controller
public function search(){
$search = Input::get('term');
$books = Book::where('title','like','%'.$search.'%')->get();
foreach ($books as $book) {
$data[] = $book->title;
}
// return $books;
return $data;
}
route
Route::get('auto_complete', 'BooksController#search');
CONTROLLER
public function search(){
$search = Input::get('term');
// return $search or dd($search) check if request get the value please
$books = Book::where('title','like','%'.$search.'%')->get();
// return $books or dd($books) check if request get the values please
$results = array();
foreach($books as $key => $v){
$results[]=['id' => $v->id];
}
// return a json object
return response()->json([
'suggestions'=>$results]);
}
JS
$(function() {
$( "#books" ).autocomplete({
source: 'auto_complete',
onSelect: function (data) {
location.href = "www.yourwebsite.com+data.suggestions.id" // this redirect for example book id:1 to www.yourwebsite.com/1
// Or use jquery to redirect: window.location.replace("http://stackoverflow.com");
}
});
});
Use the same route, let me know if there is some error in network or console!
I supposed that you integrated the jquery library and autocomplete library js :)
When I'm on my DeskAlert creation page, I wish to open in a dialog box a partial view which contains a list of Alert Template. So I have put a link to open a JqueryUI dialog, and I'm trying to link my Template partial view with it.
But... I don't understand why the view didn't show up, in the dialog box.
I have created Controller/View with VS 2013 assistant. Could you explain me this mecanism ?
Thanks
RouteConfig
routes.MapRoute("Index",
"AlertTemplatesModal/Index/",
new { controller ="AlertTemplatesModal",action="Index"},
new[] {"WebAppDeveloppement.Controllers"});
Create.cshtml
<script type="text/javascript">
$(document).ready(function() {
$(".tlist").on("click",function (event) {
event.preventDefaut();
$('#myDialogContent').dialog("open");
});
$('#myDialogContent').dialog({
autoOpen:false,
height:500,
width:500,
modal:true,
open:function () {
$.ajax({
url:"#(Url.RouteUrl("Index"))",
type:"GET",
succes:function(data)
{
$('#myDialogContent').html("");
$('#myDialogContent').html(data);
},
error:function(xhr,ajaxOptions, thrownError){
alert("error");
}
});
},
buttons:{
Cancel:function() {
$(this).dialog("close");
}
}
});
});
</script>
<div id="myDialogContent"></div>
AlertTemplatesModalController
private DSdatabaseEntities db = new DSdatabaseEntities();
public ActionResult Index()
{
var alertTempalte = db.AlertTemplate.Include(a=>a.AlertMode).Include(a=>a.AlertPriority).Include(a=>a.RecipientMap);
return View(alertTemplate.ToList());
}
Index.cshtml
#model IEnumerable<WebAppDeveloppment.AlertTemplate>
<div id="myDialogContent">
...
</div>
Ok, I've found the solution. Your response give me the idea to test with Firebug... and I could see my error. I make a confusion in the url syntax between Controller/Action/View. So I have created a special action, a partialview, and finally, it's worked.
This link helps me to understand : http://www.itorian.com/2013/02/jquery-ui-autocomplete-with-json-in-mvc.html the logic, and this one : Loading a partial view in jquery.dialog how to call partial view. My solution :
Create.cshtml
<script type="text/javascript">
$(document).ready(function() {
$(".tlist").on("click",function (event) {
event.preventDefaut();
$('#myDialogContent').dialog("open");
});
$('#myDialogContent').dialog({
autoOpen:false,
height:500,
width:500,
modal:true,
open:function () {
$(this).load("/AlertTemplatesModal/TemplateView/");
},
buttons:{
Cancel:function() {
$(this).dialog("close");
}
}
});
});
</script>
<div id="myDialogContent"></div>
AlertTemplatesModalController
public ActionResult TemplateView()
{
ViewBag.AlertTemplateTitle = new SelectList(db.AlertTemplate,"AlertTemplateID","AlertTemplateTitle");
return PartialView("Index");
}
I have changed the code little bit. Created a function to load partial view in div and created a parameter for callback function so that when partial view is loaded, you could apply jquery dialog on that div. Give it a try and let me know.
<script type="text/javascript">
$(document).ready(function() {
$(".tlist").on("click",function (event) {
event.preventDefaut();
loadPartialView(function(){
$('#myDialogContent').dialog("open");
});
});
$('#myDialogContent').dialog({
autoOpen:false,
height:500,
width:500,
modal:true,
buttons:{
Cancel:function() {
$(this).dialog("close");
}
}
});
});
function loadPartialView(callback){
$.ajax({
url:"€(Url.RouteUrl("Index")}",
type:"GET",
succes:function(data)
{
$('#myDialogContent').html("");
$('#myDialogContent').html(data);
callback();
},
error:function(xhr,ajaxOptions, thrownError){
alert("error");
}
});
}
</script>
I am using knockout to render a page with rows of data. On each row there is a link which should call a controller function which returns a partial view.
knockout script for link is (inside foreach loop)...
<a class="lnkEdit" data-bind="attr: {'href': '#Url.Action("ControllerActionName", new RouteValueDictionary() { { "Controller", "ControllerName" } })/'+ id}">Details</a>
Script section...
$(document).ready(function () {
$.ajaxSetup({ cache: false });
$("#dialog-edit").dialog({
title: 'Details',
autoOpen: false,
resizable: false,
position: ['center', 50],
width: 700,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
$(".ui-dialog-titlebar-close").hide();
$(this).load(url);
}
});
$(".lnkEdit").on("click", function (e) {
url = $(this).attr('href');
$("#dialog-edit").dialog('open');
return false;
});
$("#btncancel").on("click", function (e) {
$("#dialog-edit").dialog("close");
return false;
});
ko.applyBindings(new UnitViewModel());
})
My page has div as place holder for dialog...
<div id="dialog-edit" style="display: none">
Problem: When I click on link for details; the controller returns partial view but jquery is not able to generate dialog so the page opens as normal view. What is wrong with this?
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
I'll Check Your code and is working...
just add CSS and JS proper.
I've ran into an issue with CKEditor 4 and jQuery UI's sortable method where if I sort a container that has a CKEditor instance, it removes the value and throws an error "Uncaught TypeError: Cannot call method 'getSelection' of undefined". It also makes the editor uneditable. I was able to get around this in CKEditor 3 with one of the following hacks found here:
CKEditor freezes on jQuery UI Reorder
In looking at the Chrome DOM inspector, it appears that the contents of the iframe are removed.
Below is crude test code:
<html>
<head>
<title>test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js"></script>
<script src="ckeditor.js"></script>
<script type="text/javascript">
$(function(){
var tmpStore = {};
$('#sortable').sortable({
cursor: 'move',
// Hack that use to work on V3 but not on V4:
// https://stackoverflow.com/questions/3379653/ckeditor-freezes-on-jquery-ui-reorder
start:function (event,ui) {
$('textarea').each(function(){
var id = $(this).attr('id');
tmpStore[id] = CKEDITOR.instances[id].getData();
})
},
stop: function(event, ui) {
$('textarea').each(function(){
var id = $(this).attr('id');
CKEDITOR.instances[id].setData(tmpStore[id]);
})
}
});
$('textarea').each(function(){
var ckId = $(this).attr('id');
config = {};
CKEDITOR.replace(ckId, config);
})
})
li { padding: 10px; width: 800px; height: 300px; }
</head>
<body>
<ul id="sortable">
<li><textarea id="test1" name="test1">test1</textarea></li>
<li><textarea id="test2" name="test1">test2</textarea></li>
<li><textarea id="test3" name="test1">test3</textarea></li>
</ul>
</body>
</html>
I was facing the same problem and have fixed based on answers here. Please see fiddles below
ISSUE:
https://jsfiddle.net/33qt24L9/1/
$(function() {
$( "#sortable" ).sortable({
placeholder: "ui-state-highlight"
});
CKEDITOR.replace( 'editor1' );
CKEDITOR.replace( 'editor2' );
CKEDITOR.replace( 'editor3' );
CKEDITOR.replace( 'editor4' );
});
RESOLVED ISSUE: https://jsfiddle.net/57djq2bh/2/
$(function() {
$( "#sortable" ).sortable({
placeholder: "ui-state-highlight",
start: function (event, ui)
{
var id_textarea = ui.item.find(".ckeditor").attr("id");
CKEDITOR.instances[id_textarea].destroy();
},
stop: function (event, ui)
{
var id_textarea = ui.item.find(".ckeditor").attr("id");
CKEDITOR.replace(id_textarea);
}
});
CKEDITOR.replace( 'editor1' );
CKEDITOR.replace( 'editor2' );
CKEDITOR.replace( 'editor3' );
CKEDITOR.replace( 'editor4' );
});
EDIT: If like me you had seperate configs per editor here's updated code that will help:
start: function (event, ui)
{
$('.wysiwyg', ui.item).each(function(){
var tagId = $(this).attr('id');
var ckeClone = $(this).next('.cke').clone().addClass('cloned');
ckeConfigs[tagId] = CKEDITOR.instances[tagId].config;
CKEDITOR.instances[tagId].destroy();
$(this).hide().after(ckeClone);
});
},
stop: function(event, ui) {
// for each textarea init ckeditor anew and remove the clone
$('.wysiwyg', ui.item).each(function(){
var tagId = $(this).attr('id');
CKEDITOR.replace(tagId, ckeConfigs[tagId]);
$(this).next('.cloned').remove();
});
}
Thanks to: https://github.com/trsteel88/TrsteelCkeditorBundle/issues/53
You have to re-create CKEditor once underlying DOM structure is modified. Save editor data with editor.getData() before editor.destroy() and restore contents with editor.setData( data ) once you create a new instance. There's no other way to fix this since CKEditor strongly depends on the DOM structure.
Remove CKEditor start Sortable
var ckeConfigs = [];
$('.ui-sortable').sortable({
start:function (event,ui) {
$('.lineItemCommentBox', ui.item).each(function(){
var tagId = $(this).attr('id');
ckeConfigs[tagId] = CKEDITOR.instances[tagId].config;
CKEDITOR.instances[tagId].destroy();
});
},
stop: function(event, ui) {
$('.lineItemCommentBox', ui.item).each(function(){
var tagId = $(this).attr('id');
CKEDITOR.replace(tagId, ckeConfigs[tagId]);
});
}
});
The code below works for me, we have to destroy the editor on start and recreate it when the drag is ended getting the value of the textarea which come the data from :
jQuery(function($)
{
var panelList = $("#nameofyourdiv");
panelList.sortable(
{
handle: ".classofyourdivforsorting",
start: function (event, ui)
{
var id_textarea = ui.item.find("textarea").attr("id");
CKEDITOR.instances[id_textarea].destroy();
}
stop: function (event, ui)
{
var id_textarea = ui.item.find("textarea").attr("id");
CKEDITOR.replace(id_textarea);
}
});
});
Hope it helps someone.
i ve solved this kind of problem by instantiating the CKEditor after having opened the jquery dialog
I had the Similar issue with CKEDITOR , The Code Below worked for me. Destroy the Ckeditor instance and Remove the Ckeditor and when the dragging ends replace the current textarea with Ckeditor again
$("#sortable").sortable({
items: '.dynamic',
start: function (event , ui) {
var editorId = $(ui.item).find('.ckeditor').attr('id');// get the id of your Ckeditor
editorInstance = CKEDITOR.instances[editorId]; // Get the Ckeditor Instance
editorInstance.destroy(); // Destroy it
CKEDITOR.remove(editorId);// Remove it
},
stop: function(event, ui) {
var editorId = $(ui.item).find('.ckeditor').attr('id');// Get the Id of your Ckeditor
CKEDITOR.replace(editorId);// Replace it
}
}
});
$("#sortable").disableSelection();
Here #sortable is the id of the DIV which is sortable and '.dynamic' is the Class assigned to DIV that are eligible to sort and '.ckeditor' is the class for the Textarea .
I got my solution from Here , Hope this helps for someone in future.
I simply use the ckeditorOff() and ckeditorOn() functions to keep data and re/de-instance ckeditor instances during movement.
$('#sortable').sortable({
cursor: 'move',
start:function (event,ui) {
if(typeof ckeditorOff=='function')ckeditorOff();
},
stop: function(event, ui) {
if(typeof ckeditorOn=='function')ckeditorOn();
}
});
I put the typeof ckeditorOff statement to make the code compatible with future versions of ckeditor in case they decide to remove these two functions.
How to generate a javascript link in asp.net mvc?
eg.
Pop it
Can I use Html.ActionLink and how to do this?
I could do something like this:
Pop it
But I just want to find out will there be some better solutions for this?
Many thanks.
Yes, you can do something like:
<%=Html.ActionLink(model.Title, "View", "PoppedView", new { Id = model.Id.ToString() }, new { target="_blank" })%>
I would look at doing this using jQuery UI and a dialog instead of a new window. You can use the open handler to load up the content into the dialog.
<%= Html.ActionLink( "Pop It",
"ItemDetail",
"Item",
new { ID = model.ID },
new { #class = "popup-link" } ) %>
<script type="text/javascript">
$(function() {
$('.popup-link').click( function() {
var href = $(this).attr('href');
$('<div><p class="popup-content"></p></div>').dialog({
autoOpen: true,
modal: true,
height: 200,
width: 400,
open: function() {
$(this).find('.popup-content').load(href);
},
close: function() {
$(this).dialog('destroy');
}
});
return false;
});
});
</script>