I am working in ASP.NET MVC 3 and using Telerik. I have an empty telerik window. My goal is to only ask server for content when the user clicks a button, however I have no idea how this could be done. I imagine that to accomplish this I would need to store a reference to the telerik window in question. But how do i do this? plz help. This is how far I have got:
#{
Html.Telerik().Window()
.Name("ImportDialog")
.ClientEvents(events => events.OnOpen("DialogOpen"))
.Visible(false)
.Title("Import users")
.Draggable(false)
.Resizable(resizing => resizing.Enabled(false))
.Modal(true)
.Width(400)
.Height(400)
.Render();
}
I do want do do somethin in DialogOpen function, or alternatevly replace that client side function with a server side funciton....
You should use the client API of the Telerik Window and more specifically the ajaxRequest method.
So for example when the button is clicked you should get the client object and call the ajaxRequest method which will make the Window retrieve its content from that MVC action method.
e.g.
function DialogOpen(){
var myWin= $('#ImportDialog').data('tWindow');
myWin.ajaxRequest("Controller/Action", { name: "John",location:"Boston"});
}
I found one type of answer, however i am not sure yet if it is the best.
In the javascript function DialogOpen I send an ajax request to an url(also known as an Action of a Controller in MVC), the I put the result in the content of the dialog window, like so:
function DialogOpen ()
{
$.ajax({
type: "POST",
url: "Controller/Action",
data: "name=John&location=Boston",
success: function (htmlContent)
{
$('#ImportDialogContent').html(htmlContent);
},
error: function ()
{
$('#ImportDialogContent').html("<p>Could not import user data at this time</p>");
}
});
}
P.S.: I gave an ID to content area of telerik Window(ImportDialogContent)!
Related
I have created a web calendar using HTML,CSS and C# in an MVC application. The HTML is in a view and I have a controller with an action that initializes the Calendar and displays the correct days on the view.
It works as intended but the problem comes from the fact that I want to embed this calendar to a couple of pages in unrelated Views controlled by different actions and with different models loaded.
I could copy paste the view code and make the necessary adjustments to the model but that would not be ideal. I tried with RenderAction but the problem is that when I use the buttons to navigate to different months I leave the initial view. e.g.:
#Html.ActionLink("‹", "Calendar",
new { month = Model.RequestedDateTime.Month - 1, year =
Model.RequestedDateTime.Year })
Is there a way to modify this behavior?
Thanks
Html.ActionLink, alway creates a normal link, with have the common behaviour. If you want to share your calender.
To avoid redundant code, you may redesign the calender as a partial view and replace the link by a label for example. Bind an ajax function to the label-click-event to refresh the calender. Something like:
#Html.Label("<", new { onclick="pageMonthBack("+Model.RequestedDateTime.Month - 1+", " Model.RequestedDateTime.Year+");" })
I would place the called ajax functions in a script which is loaded separately.
I solved the problem in a similar way, to what developer10214 proposed. I used a div and in that I used Render.Action. Then I used the following code
$(function () {
$("#cal").on('click', "#backwards", function () {
$.ajax({
url: "Home/Calendar?target=backwards",
cache:false,
type: "GET",
success: function (result) {
$("#cal").html(result);
}
});
});
});
in the including page. And I did not use ActionLink at all.
I've been searching for a way to update data using a modal pop-up.
Right now I'm using devexpress, because we're already using other devexpress controls (but this could change if a jquery library would be easier!!)
I'm stuck with the validation aspect. Frankly, the entire process seems quite hard for what I'm trying to achieve.
Anyways, let me describe the process that I've currently worked out:
-The Index page contains an overview of the different elements that can be updated. Using a HtmlExtension, I was able to create a devexpress popup which loads the edit page when you open the popup. => #Html.PopupControl().WithText("Edit").PopupGoesTo(Url.Action("EditPopup", etc etc)
-The edit page -which is just a partial view- works just fine.
I've created a little test page, which contains 1 textbox, which takes in a decimal.
I want to submit the form using ajax (because frankly, I have no idea how I can show the validation if I do a full post back, since I need to be able to create the popup and bind the data to it AND trigger the validation errors).
<script type="text/javascript">
function EndPopUpUpdate(message) {
if (message.url) {
window.locatin.href = url;
}
$("#submitButtonPopUp, #loadingPopUp").toggle();
}
function BeginPopUpUpdate() {
$("#submitButtonPopUp, #loadingPopUp").toggle();
}
</script>
using (Ajax.BeginForm("Edit", "xxx", new AjaxOptions { UpdateTargetId = "PopUpDiv", HttpMethod = "Post", OnBegin = "BeginPopUpUpdate", OnComplete = "EndPopUpUpdate"}, new { id = "PopUpForm" }))
{
<div id="PopUpDiv">
#Html.Partial("EditPopup", new xxxViewModel())
</div>
}
I was able to achieve validation when I postback by manually rehooking the jquery events (because these don't get hooked since the page gets loaded dynamicly)
function ReconnectValidation() {
$("#PopUpForm").ready(function () {
$.validator.unobtrusive.parse("#PopUpForm");
});
$("#submitButton").click(function (e) {
var form = $("#PopUpForm");
if (!form.valid()) {
e.preventDefault();
}
});
}
So this handles my client side validation, which works.
Now, my actual problem! Server side validation.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([ModelBinder(typeof(CommandModelBinder))] UpdateCommand command)
{
if (!ModelState.IsValid)
{
//using the command pattern
var handlerResult = HandlerLocator.GetQueryHandler<IGetOverviewHandler>().Execute(..);
return PartialView("EditPopUp", handlerResult.ViewModel);
}
HandlerLocator.GetCommandHandler<UpdateCommand>().Handle(command);
var returnLink = Url.Action("Index", new {..});
return Json(new { url = returnLink }, JsonRequestBehavior.AllowGet);
}
I've written a CustomModelBinder, which does nothing but look for the properties in my command object (my return model if you will) and looks in the formcollection if it can find a matching object with the same name. Then it tries to convert it and it binds a ModelError to my ModelState if it fails.
So, now we have a ModelState which is either valid or is invalid.
If it's valid, I want to redirect to the Index (so my overview can update). I've read that I should handle this in the client side, because the ajax.BeginForm is going to replace the
"PopUpDiv"-div with the result (which just creates the same page within my page).
Here is the onComplete event:
function EndPopUpUpdate(message) {
if (message.url) {
window.locatin.href = url;
}
$("#submitButtonPopUp, #loadingPopUp").toggle();
}
The problem is, that I don't receive a json message, but I receive a PartialView. This means I can't access the message.url..because that's not what I recieve :/
So that is problemo number 1
If the object is not valid, I want to return a partialview with the model and give an error to the user. When I return the partialview, it just replaces the current view but it doesn't show any validation errors..
That is problem number 2 :)
Also, if you know a better way to solve this problem, please don't hesitate to respond (because this method just seems really convoluted for what it does -or should do-)
Sorry for the lengthy post, but I hope everything is clear.
Thanks for your help & time!
I've used the dialog plugin from jQuery UI () before, which I've found works well. I normally get the links to open up in an iframe within the popup, which avoids the problem you describe where the jQuery validation events don't get hooked up because the page gets loaded dynamically - both client side and server side validation should work as normal, just within this iframe.
The nice thing about this technique is that you can generate action links as normal within your index page, just add a class of popup to them e.g.
#Html.ActionLink("Edit", "Edit", new { id = Model.Id }, new { #class = "popup" })
Then, you can get these links to open in a dialog iframe with jQuery like:
$("a.popup").click(function(e) {
e.preventDefault();
$("<iframe />").attr("src", $(this).attr("href") + "?popup=true").dialog({ show: "fadeIn", modal: true, width: 300, height: 300});
});
This basically looks for popup links, cancels the default behaviour (page navigation) and opens that URL in a iframe within a popup, adding a querystring to identify that the page is within a popup. The reason for this querystring and knowing its a popup allows you to load a different layout page within the view, maybe through an action filter e.g.:
public class Popup : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Result != null
&& filterContext.Result is ViewResult
&& filterContext.RequestContext.HttpContext.Request["popup"] == "true")
(filterContext.Result as ViewResult).MasterName = "~/Views/Shared/_PopupLayout.cshtml";
}
}
This means you can easily apply this attribute to classes where you want action methods to apply. This method also means if you change your mind about the implementation in the future (ie removing the popups) then you can easily remove the jQuery that cancels the clicks and your app will continue to function as a normal MVC app with separate pages, and all the navigation/validation etc will 'just work'.
I hope that all makes sense and helps.
I am using Asp.Net/C# in my project.I am using Forms Authentication.Currently I call FormsAuthentication.SignOut() on click of Asp.Net button.It works well , but my requirement is that I need to log out a user from horizontal menu option
Logout
That would be Html menu , so how do I call FormsAuthentication.SignOut() method when a user clicks Logout from the menu bar.Is there any solution possible or any other technique.
Any suggestions are welcome.
Thanks
FormsAuthentication.SignOut() is a server side code and you cannot directly invoke it from client side (i.e. browser) - instead, you need to create a URI that will do the same for you.
For example, you can have AJAX service that will call above code or simply speaking, you can have logout.aspx page that will call FormsAuthentication.SignOut() in say page_load. Such a URI can be invoked from jquery to get you what you want.
In your case, you should simply have a link to logout aspx page in your logout menu (or in menu click, write document.location = "/logout.aspx" which essentially means navigating to log-out page).
here you go:
$('#logout').click(function () {
$.ajax({
url: '/logout',
success: function () {
document.location = '/logged_out';
}, error: function () {
alert('Logout failed');
}
});
return false;
});
I am using Telerik tree view control:
http://demos.telerik.com/aspnet-mvc/treeview
http://demos.telerik.com/aspnet-mvc/treeview/clientsideevents
What I want to do is set up this control on the left, then a "panel" on the right, that is a view that updates when the treeview is clicked.
So I want to do AJAX call to retrieve info from DB when a click is made in the tree view. Then I can update the "panel" with information on the current item.
How could I go about building this "panel" ? And any controls that are designed for ASP.NET MVC2 are better as that is what I am implementing this in. I saw something called UFRAME but it reminded me of IFRAME and thought I should probably avoid it.
Can I do this with a partial view, and then just the partial view area of the page updates ?
Thanks.
Telerik TreeView has:
OnSelect client side event that
you want to subscribe to and
issue an Ajax call when select happens
to your Asp.net MVC application controller action that
would return a PartialView which
you can then append to right panel
That's the process to be developed.
I've never used Telerik's controls in my life but based on the documentation on their page it seems that it works this way. Everything is basically the usual Asp.net MVC + jQuery except for the OnSelect client side event that you have to use. So nothing particularly complicated as long as Telerik's controls work as expected (which can be a story of its own).
Some code
Since I've never used Telerik, I still think this can be done something along the line:
You have your TreeView defined in one of your views like:
<%= Html.Telerik().TreeView().Name("ClientSideID") %>
Then use jQuery to do the rest:
$(function(){
$("#ClientSideID").bind("select", function(e){
e.preventDefault();
$.ajax({
url: "SomeURL",
data: e.item,
type: "POST",
success: function(partialView) {
partialView = $(partialView);
$("RightPanelSelector").append(partialView);
},
error: function(xhr, status, err){
// handle error
}
});
});
});
This code isn't tested but will get you started.
I need to be able to do two things with Javascript or JQuery, without involving third-party open source libraries:
Use a jQuery or Javascript function to fill the HREF attribute of a link.
Perform an HTTP Get or Post operation OnUpdate of a text box or combo box (using the above javascript function to specify the HTTP target)
The end result will be hyperlinks posted to the controller that look similar to this:
http://mydomain/addresses/1?order=name&state=ca
The controller will return a new page, ordered by name and filtered on the state of California.
Suggestions?
If you have 2 textboxes and a hyperlink with url, try something like:
$(document).ready(function() {
$('a#yourHyperLinkId').click(function(event) {
event.preventDefault();
var url = $(this).attr('href');
var order = $('input#order').val();
var state = $('input#state').val();
$.get(url, { order: order, state: state }, function(response) {
$('div#yourDivForResponse').html(response);
});
});
});
I am not sure I follow...
Why do you need to fill the HREF of the link if your going to use JQuery to do the postback anyway?
Some elements of answer here : Passing Javascript variable to <a href >
If you want to load the controller response in the window, you can use a form with a crafted action. If not, you can either use an iframe as a target to the form or use an XHR object. Whatever solution you choose, you will link it to the onchange event of the text box or combo box.
Thanks fellas for pointing me in the right direction.
Answer to #1:
document.getElementById("link2").setAttribute("href",strLink);
Answer to #2 (more or less):
$("#mySelect").change(function() {
document.location = this.value;
});