Jquery event in ASP MVC 3 Web Application - c#

I am developing an ASP.Net MVC 3 application using C# and SQL Server 2005.
I would like to create a Jquery event on a button. It's like an accordian animation.
I have already in the template which I used an example and I want to remake it in an another button.
This is a video describing the event.
Sorry, I didn't post any code because I don't find really where is the script of this event.
But, I will edit my post for any demand.
Thanks for understanding :)
this is The view Gestion which I would like to show when I click on the button :
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication2.Models.FlowViewModel>" %>
<asp:Content ID="loginTitle" ContentPlaceHolderID="TitleContent" runat="server">
Gestion
</asp:Content>
<asp:Content ID="loginContent" ContentPlaceHolderID="MainContent" runat="server">
<h2>GĂ©rer</h2>
</asp:Content>
This is a class GestionHelper which I created following the example of the other button :
namespace Helpers
{
public static class GestionHelper
{
public static string GestionLinkHelper(this HtmlHelper helper){
string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
string currentActionName = (string)helper.ViewContext.RouteData.Values["action"];
var sb = new StringBuilder();
sb.Append("<div id=\"gestionlink\">");
sb.Append(helper.ActionLink("aaaaa", "Gestion", "Anouar"));
sb.Append("</div>");
return sb.ToString();
}
}
}
I creat a new Controller named AnouarController :
namespace MvcApplication2.Controllers
{
[HandleError]
public class AnouarController : Controller
{
//
// GET: /Anouar/
public ActionResult Gestion()
{
return View();
}
}
}
and finally,,,this is what I add in the View of the link (which allow the action):
<%= Html.GestionLinkHelper() %>

If I understand you, add a button and your target div
<input type="button" value="Show Gestion" id="btnShowGestion" />
<input type="button" value="Hide Gestion" id="btnHideGestion" />
<div id="divGestion"></div>
Add your JQuery On Ready
<script type="text/javascript">
$(document).ready(function() {
$('#divGestion').load('/Anouar/Gestion');
$('#btnShowGestion').click(function() { $('#divGestion').show() });
$('#btnHideGestion').click(function() { $('#divGestion').hide() });
});
</script>
Not knowing what Ajax action you wanted to perform, I assumed you wanted to load a partial view into a div.

Related

How do I set a click event in C#?

I am new to C# (my job is making me convert from JavaScript) and for some reason I cannot find a straightforward example of setting up a button that calls a method.
I am using C# ASP.NET MVC 2 with the ASPX view engine. This is not ASP.NET Web Forms.
My Index.aspx looks like:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Blogs
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Blogs</h2>
<button ID="btnBlog" onclick="blogging" runat="server">Blog</button>
</asp:Content>
and I have tried several ways of doing this; this last one being:
public event EventHandler blogging()
{
System.Diagnostics.Debug.Write("clicked");
}
Edit:
Ok so doing the button like:
<asp:Button ID="btnBlog" OnClick="blogging" runat="server" />
and method:
protected void blogging(object sender, EventArgs e)
{
System.Diagnostics.Debug.Write("clicked");
}
Tells me that blogging is undefined... how do I call blogging()?
If you meaning to call an action method from View then you might try to use one of the following examples below. When creating a link to a controller action in ASP.NET MVC, using the generic ActionLink method is preferable, because it allows for strongly typed links that are refactoring friendly.
Default: ActionLink:
#Html.ActionLink("Delete", "Delete", new { id = item.ID })
However, what if we want to have an image that links to an action? You might think that you could combine the `ActionLink` and Image and `Button` helpers like this:
Using Button:
<button onclick="location.href='#Url.Action("Index", "Users")';
return false;">Cancel</button>
(with parameters)
<button onclick="location.href='#Url.Action("Detail", "Admin",
new { Model.ProductID })';return false;">Detail</button>
or
<input type="button" title="Delete" value="Delete"
onclick="location.href='#Url.Action("Delete", "movies", new { id = item.ID })'" />
**Using Image:**
<a href="#Url.Action("Delete", "movies", new { id = item.ID })" title="Edit">
<img src="../../Content/Images/Delete.png" />
</a>

How to use MVC Model binding with an Angular ng-bind attribute

In my view I have a tag with an ng-bind attribute that is showing the correct boolean value:
<span id="ShowFlag" name="ShowFlag" ng-bind="session.view.showFlag"></span>
When the form is posted on the server side I would like to bind this to a property on the relevant model.
public bool ShowFlag { get; set; }
However, this is always returning false, whereas the value shown in Span tag is showing correctly as true on the page. Is there something obvious I'm missing here?
I think you're something you're missing about how AngularJs binding works. if you want to get a value from the server into an angular model you can use Razor to get that data into JavaScript (the best place is in your Angular controller.)
Here is a quick sample I put together.
This is code from the MVC Controller. In this example we are using Model data and ViewBag data.
public ActionResult Index()
{
dynamic model = new ExpandoObject();
model.ShowFlag = "True";
ViewBag.ShowFlag = "ViewBag True";
return View(model);
}
This is what the view looks like including reference so Angular, JQuery and the code for the AngularJs app and controller:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Demo</title>
</head>
<body>
<div>
<h2>Sample For Stack Overflow</h2>
<div ng-app="glennapp">
<div ng-controller="testController">
<input type="text" ng-model="showFlag" />
<input type="text" ng-model="showFlag2" />
<div>
<span ng-bind="showFlag" ></span>
<span ng-bind="showFlag2" ></span>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="//code.angularjs.org/1.4.8/angular.min.js"></script>
<script type="text/javascript">
var mainApp = angular.module('glennapp', ['glennControllers']);
var glennControllers = angular.module('glennControllers', []);
glennControllers.controller('testController', ['$scope', function ($scope) {
$scope.showFlag = '#ViewBag.ShowFlag';
$scope.showFlag2 = '#Model.ShowFlag';
}]);
</script>
</body>
</html>
Another option would be to create an MVC action that returns JsonResult and then write some JavaScript to make an Ajax call and retrieve the data.
When posting a form only input and select tag values are passed to the server
in you case ShowFlag is a span, so you need to make it an input:
<input type="checkbox" id="ShowFlag" name="ShowFlag" ng-bind="session.view.showFlag"/>
If you are posting to server with ajax, make sure that you serialize your model properly:
for example for the following action:
public ActionResult (FlagsConatiner container)
{
//
}
public class FlagsConatiner
{
public bool ShowFlag { get; set; }
}
Serialized model should look like this:
{
"ShowFlag":"true"
}
As pointed out above, you must use an input for the binding to be successful. I used the following which is now working:
<input type="hidden" id="ShowFlag" name="ShowFlag" ng-value="session.view.showFlag">

How To pass Field Value (like textbox) from Partial view to other Partial view

Can you help on this
I have two Partial Views in the page, the First Partial View have (Input Text and Submit Button )
Whenever the user Press Submit Button (from PartialView1 ) , I would like to ready the input Text from PartialView2
can you please help on How I can Read the Partial View1's Input Text from PartialView2 when Pressing the PartialView1's submit button ?
More specifically :reading that value from the "Action" that is rendering the PartialView2
more Details:
It is something like that : read the values from all textboxes in partialview1 and assign the all content into textbox2 in partial2 when press submit button from PartialView1
below is an example
this is my main View index.aspx:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Index</title>
</head>
<body>
<div>
<%Html.RenderAction("ActionSenderForPartial1", "Controllername"); %>
</div>
<h2>Result</h2>
<div>
<%Html.RenderAction("ActionReceiverForpartial2", "Controllername"); %>
</div>
</body>
</html>
the PartialView 1 "Partial1"
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<MvcApplication3.Models.UIField>>" %>
<form method="post">
<%:Html.TextBox("TextBox1") %>
<%:Html.TextBox("TextBox2") %>
.
.
<%:Html.TextBox("TextBoxN") %>
<p>
<button name="btnaction" value="search">Search</button>
<button name="btnaction" value="cancel">Cancel</button>
</p>
</form>
for PartialView2: "Partial2.ascx"
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%:Html.TextBox("TextBox2") %>
The actions "" & "" :
[ChildActionOnly]
public ActionResult ActionSenderForPartial1()
{
return PartialView();
}
[ChildActionOnly]
public ActionResult ActionReceiverForpartial2(string btnaction)
{
string _searchQuery = string.Empty;
--How to read the all TextBoxes contents from PartialView1 and assign the concatenated values to the TextBox2 at this partialview2
return PartialView();
}
In case there is many options I would highly appreciate to mention advising the best one as I am new in MVC.
Thanks so much
if any actual example will be highly appreciated
Please Note: i Have an idea on how to do it by Ajax but I would to do it without using Ajax .
Many Thanks
Nahed

Getting and setting ASP.NET attributes in jquery

I am adding a new attribute to a DataList control in asp.net. I want to set the attribute on the server in C#. I then want to modify it in jQuery on the client, and get the new value of the attribute in C# back on the server. I think if I initialize the attribute to say "0" in my .aspx code, it get reset to "0" during the postback.
So, I'm using DataList.Attributes.Add() to create and init the attribute value during my render. On the client, I use .attr in jQuery to modify the value. During the postback on the server, I use DataList.Attributes["attributeName"] to get the new value, but it's null. I've changed EnableViewState for the DataList, its parent, and grandparent to true and false, but I still get a null value.
Is there a way to create and init an attribute on the server, modify it in jQuery on the client, and get the new value in C# back on the server?
A server control's attributes are persisted in the page viewstate. On postback the server control is re-created, and, its attribute values are re-created by parsing the viewstate value, from the posted data.
Hence any attempt to modify a server-created-control-attribute, or, add an attribute on a server-control from the client will not work. (More precisely it won't be very straight forward even if it might be possible).
Anyhow, a browser is "programmed" to send (over the wire) data held inside any html input or select control (hope I didn't miss anything) nested inside the html form. Further, all such controls need to be identified by the value specified by the name attribute. For e.g.
<form method="post" action="default.aspx">
<input type="text" name="foo" value="123"/>
<input type="submit" value="submit to server"/>
</form>
If one such form is submitted to a server like ASP.NET (which is an abstraction of IIS which implements the CGI standard), you can get the value of the textbox by doing something like:
string fooValue = Request.Form["foo"];
A browser program is usually programmed to send data corresponding the name and value attributes only.
Now, since you are looking at getting more than one kind of data on the server, but still associated with a single control, your options are to go with any of the following:
Access the value from two separate controls on the server. However, its your job to figure their are associations.
You can think of a user control approach, which ultimately is like the above but if written will give you a neat encapsulation.
Here is a small example of the 2nd approach:
CompositeControl.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="CompositeControl.ascx.cs" Inherits="WebApp.Attributes.CompositeControl" %>
<label>Enter Name</label>
<asp:TextBox runat="server" ID="tbxName"></asp:TextBox>
<asp:HiddenField ID="hdnAge" runat="server" />
CompositeControl.ascx.cs:
using System;
namespace WebApp.Attributes
{
public partial class CompositeControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (!string.IsNullOrEmpty(this.HiddenFieldClientId))
{
hdnAge.ClientIDMode = System.Web.UI.ClientIDMode.Static;
hdnAge.ID = this.HiddenFieldClientId;
}
}
public string Name
{
get
{
return tbxName.Text;
}
set
{
tbxName.Text = value;
}
}
public int Age
{
get
{
return int.Parse(hdnAge.Value);
}
set
{
hdnAge.Value = value.ToString();
}
}
public string HiddenFieldClientId { get; set; }
}
}
default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="WebApp.Attributes._default" %>
<%# Register src="CompositeControl.ascx" tagname="CompositeControl" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-2.1.0.min.js"></script>
<script>
$(function () {
$('#tbxAge').val($('#personAge').val());
$('#btnSetAge').click(function () {
$('#personAge').val($('#tbxAge').val());
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:CompositeControl ID="CompositeControl1" runat="server" HiddenFieldClientId="personAge" />
<br />
<input id="tbxAge" type="text" />
<input id="btnSetAge" type="button" value="Set" />
<p>Hit <strong>set</strong> before clicking on submit to reflect age</p>
<asp:Button runat="server" ID="btnSubmit" Text="Submit"
onclick="btnSubmit_Click" />
<br />
<asp:Literal runat="server" ID="ltrlResult"></asp:Literal>
</div>
</form>
</body>
</html>
default.aspx.cs:
using System;
namespace WebApp.Attributes
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CompositeControl1.Age = 23;
CompositeControl1.Name = "Default";
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
ltrlResult.Text = string.Format("<p>{0}</p><p>{1}</p>", CompositeControl1.Name, CompositeControl1.Age);
}
}
}
You could make an AJAX call in wich you send the changes made it with jquery to some webservices method in your code behind to handle it.
AJAX jquery post change call:
$.ajax({
type: 'POST',
url: 'Default.aspx/Checksomething',
data: '{"userValuePostChanged ": "' + DtLValue+ '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
alert("Result: " + msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus);
}
});
webservices C#
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Checksomething(string userValuePostChanged)
{
//Do some stuff with userValuePostChanged
return "something else"
}
This are the links where I took the examples:
consume .net web service using jquery
How to use jQuery to make a call to c# webservice to get return value
http://www.codeproject.com/Articles/66432/Consuming-Webservice-using-JQuery-ASP-NET-Applicat

Simple jQuery Hello World in ASPX

I really dont understand why this simple example doesnt work :S
I have a WebApplication in which I have a script :
function myAlert() {
$("#Button1").click(function () {
alert("Hello world!");
});
}
In my asp page, I have this simple code
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Graph.aspx.cs" Inherits="WebApplication.Graph" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" Width="100px"/>
</asp:Content>
And finally I register the script in the cs :
protected override void OnPreLoad(EventArgs e)
{
Page.ClientScript.RegisterClientScriptInclude("jQuery",
ResolveUrl(#"Scripts\jquery-1.4.1.js"));
Page.ClientScript.RegisterClientScriptInclude("jMyAlert",
ResolveUrl(#"Scripts\MyAlert.js"));
// check if the start up script is already registered with a key
if(!Master.Page.ClientScript.IsStartupScriptRegistered("jMyAlert"))
{
// since it is not registered, register the script
Master.Page.ClientScript.RegisterStartupScript
(this.GetType(), "jMyAlert", "myAlert();", true);
}
}
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "jMyAlert", "myAlert()", true);
}
I dont see what's wrong with this. I tried to include the scrit directly inside the aspx but nothing. I then try onto a simple html page and it works fine.
I want to use a plotting library using jQuery in my page so I'm very far to succeed if such a simple example causes me such a lot of problem...lol
Try checking the debug console within whatever browser you are using to see if "$" is undefined. It sounds like you are missing jquery when using the full ASP.NET approach.
The Id of that button is not going to be #Button1 because of the use of the master page. Try viewing the source to see what I mean.
To solve this, you will need to be able to see the actual Id in the JavaScript.
Something like this in your Page_Load method:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"Button1Id", string.Format("var Button1Id = '{0}';", Button1.ClientID), true);
Will create the following in your page:
<script type="text/javascript">
//<![CDATA[
var Button1Id = 'Button1';//]]>
</script>
Which then means that your myAlert method will need to look like this:
function myAlert() {
$("#" + Button1Id).click(function () {
alert("Hello world!");
});
}

Categories