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>
Related
I have the following script that is rendered inside my _layout view:-
$(document).ready(function () {
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: target.attr("data-autocomplete-source"),
minLength: 1,
delay: 1000
});
});
});
and i added the following field to apply autocomplete on it:-
<input name="term" type="text" data-val="true"
data-val-required= "Please enter a value."
data-autocomplete-source= "#Url.Action("AutoComplete", "Staff")" />
now if i render the view as partial view then the script will not fire, and no autocomplete will be performed, so i added the autocomplete inside ajax-success as follow:-
$(document).ready(function () {
$(document).ajaxSuccess(function () {
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: target.attr("data-autocomplete-source"),
minLength: 1,
delay: 1000
});
});
});
});
now after adding the AjaxSuccess the action method will be called, and when i check the response on IE F12 developers tools i can see that the browser will receive the json responce but nothing will be displayed inside the field (i mean the autocomplete results will not show on the partial view)?
EDIT
The action method which is responsible for the autocomplete is:-
public async Task<ActionResult> AutoComplete(string term)
{
var staff = await unitofwork.StaffRepository.GetAllActiveStaff(term).Select(a => new { label = a.SamAccUserName }).ToListAsync();
return Json(staff, JsonRequestBehavior.AllowGet);
}
EDIT2
here is the script which is responsible to show the modal popup:-
$(document).ready(function () {
$(function () {
$.ajaxSetup({ cache: false });
//$("a[data-modal]").on("click", function (e) {
$(document).on('click', 'a[data-modal]', function (e){
$('#myModalContent').css({ "max-height": screen.height * .82, "overflow-y": "auto" }).load(this.href, function () {
$('#myModal').modal({
//height: 1000,
//width: 1200,
//resizable: true,
keyboard: true
}, 'show');
$('#myModalContent').removeData("validator");
$('#myModalContent').removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse('#myModalContent');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", "disabled");
$('#progress').show();
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.ISsuccess) {
$('#myModal').modal('hide');
$('#progress').hide();
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", false);
location.reload();
// alert('www');
} else {
$('#progress').hide();
$('#myModalContent').html(result);
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", false);
bindForm();
}
}
});
}
else {
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", false);
$('#progress').hide();
return false;
}
return false;
});
}
});
First, you don't need to wrap you ajaxSuccess fucntion in ready function.
Second, it's better to use POST when you get Json from server.
I tried to seproduce your problem, but have no luck.
Here how it works in my case(IE 11, MVC 4)
script on _Layout:
$(document).ajaxSuccess(function () {
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: function (request, response) {
$.post(target.attr("data-autocomplete-source"), request, response);
},
minLength: 1,
delay: 1000
});
});
});
Controller method:
[HttpPost]
public JsonResult AutoComplete()
{
return Json(new List<string>()
{
"1",
"2",
"3"
});
}
Partial View html:
<input name="term" type="text" data-val="true"
data-val-required="Please enter a value."
data-autocomplete-source="#Url.Action("AutoComplete", "Stuff")" />
UPDATE:
I find out what your problem is. Jquery autocomplete needs array of objects that have lable and value properties. So if you change your controller code like this and it will work.
public async Task<ActionResult> AutoComplete(string term)
{
var staff = await unitofwork.StaffRepository.GetAllActiveStaff(term)
.Select(a => new { label = a.SamAccUserName, value = a.SamAccUserName })
.ToListAsync();
return Json(staff, JsonRequestBehavior.AllowGet);
}
Also you can do it on client side with $.map jquery function you can see example here
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.
How would I implement something like automatic postback for DropDownListFor in MVC. Currently, after selecting a value in dropdown I have to refresh the page to see the changes applied to the page.
In View,
The dropdownlistfor is like
#Html.DropDownListFor(m => m.SelectedItem, Model.MyItemList, new { #id = "DropDownListForId"})
and the onchange event is handled as such
<script type = "text/javascript">
$(function () {
$('#DropDownListForId').change(function () {
var item = $(this).val();
$.ajax({
url: '#Url.Action("SomeAction", "SomeController")',
type: 'GET',
data: { value: item },
success: function(result) {
}
});
});
});
</script>
Thanks!
I think you can simply achieve this by submitting form on change event of DropDownList
Assuming myForm as you form id
<script type = "text/javascript">
$(function () {
$('#DropDownListForId').change(function () {
$('form#myForm').submit();
});
});
</script>
I'm looking to add code to my Onload handler but am unsure where it would be in an MVC application?
// You may want to place these lines inside an onload handler
CFInstall.check({
mode: "overlay",
destination: "http://localhost:1414/"
});
});
The code above needs to be placed in the onload handler.
If I understand you correctly, you just need this expression below, if you are using jQuery:
<script>
$(document).ready(function() {
// Handler for .ready() called. Put your logic here.
});
</script>
or this one, without usage of jQuery:
<script>
window.onload = function(){
// Put your logic here.
}
</script>
to be included on your view.cshtml.
Here your meaning Adding Window Onload Event.
You can try this inside the js file:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
/* more code to run on page load */
});
For more information Simon Willison’s Weblog
I think you can add it just like in any other html page into your cshtml..
#{
ViewBag.Title = "Authenticate";
}
<script type="text/javascript">
$(document).ready(function () {
CFInstall.check({
mode: "overlay",
destination: "http://localhost:1414/"
});
});
</script>
<h2>Congrats..</h2>
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.