Rectangle 27 6

You can use a hiddenfield server control assign the values you need to it in javascript and assess it on server side. If you do not want post back then you can use jQuery ajax to send values.

<asp:hiddenfield id="ValueHiddenField" runat="server"/>
document.getElementById('ValueHiddenField').value = "yourValue";
string yourValue = ValueHiddenField.Value;

Using jQuery ajax and web method to send values to code behind, you can find nice tutorial over here.

$.ajax({
  type: "POST",
  url: "PageName.aspx/MethodName",
  data: {'yourParam': '123'},
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do something interesting here.
  }
});
[WebMethod]
public static void YourMethod(string yourParam)
{
   //your code goes here
}

And what mechanism gets you to the code-behind?

You need to do post back, or you can use jQuery ajax call to send values.

I think the OP is trying to avoid doing a postback, because otherwise I think they would have added a server control to the page, but I may be wrong.

How to get javascript values on code behind in c# - Stack Overflow

c# javascript jquery asp.net ajax
Rectangle 27 7

Use ClientID to get the generated Id of a server side control:

$("#<%=dateTo.ClientID%>").datetimepicker();

ASP.NET will generate a specific id attribute that is different from the id attribute of the server side control, so you need to use the generated value in order to access it from jQuery.

This spells real trouble (see: ugliness) for separating resources and ties client side script to page contents, although you could start passing around arguments to functions etc. in this format, but still.

@Grant - True. Part of the leaky abstraction of webforms :(

Indeed! A 'neat' trick, but the sooner this disappears the better. "While we provided a way of supplying the developer with the client side ID, with the growth of client side scripting this solution has become some what hacky." weblogs.asp.net/asptest/archive/2009/01/06/

@Grant - I can't agree more, but for those stuck with webforms and want to manipulate server side controls with client side script, there aren't that many other options (I suppose one could give a unique class name per such control, but that's even more hacky).

Yes, no more "but"'s from me: this is a credible answer for the OP in that situation.

javascript - runat="server" breaks my jQuery - datapicker - Stack Over...

javascript asp.net runatserver
Rectangle 27 3

To give you some encouragement, I was very new to .NET and javascript about nine months ago (and arguably still am) but I was still able to use the resources on datatables.net to make a very nice, functional datatable using ASP.net and a SQL server. A couple of suggestions:

First: The examples page, API reference, and forums on datatables.net are going to be your best resources. I've spent days coding some really complicated way to get the table to do something relatively simple only to find through the reference page that there was already an easy, sophisticated native way to do that.

Second: If you're using MVC and it's really necessary to do server side processing (if not see below), there is a great tutorial on code project about how to do set this up with datatables.net.

Third: Server side processing gives you a lot of control over the way the table renders your data, but it requires you to code sorting and pagination functions by hand. The alternative method, that I use, is the sAjaxSource initialization option for the table without bServerSide set to true -- as this allows me dynamically load the data from an external (AJAX) source, while still letting the datatable plugin do all of the heavy lifting. Here's the setup I have (I apologize if this is too simplistic):

I have an empty table in my HTML, with just the headers of each column specified. Make sure you have the thead and tbody tags.

In your .NET project, create a new "Generic Handler" (the extension should be .ashx). This handler will handle a request from your main page for your data (you'll see below). Here, I do the following:

b. Retrieve the view of the table I'm looking for

c. Parse each row into an object (I created a new class for this)

d. Serialize an array of my "row objects" into a JSON object (as this will be the easiest way for the datatable to work with your data

e. Write the response back to the page

I'd be happy to share my code that I use to do this, but I can already feel this post becoming too long, so just let me know if you want it.

I then setup my datatable in the page's javascipt, within the $(document).ready function. I use the .ashx file as my AJAX source and then I specify the name that I use as the key for each column in my JSON object - using the mDataProp option:

oTable = $("#production_table").dataTable({            
    "sAjaxSource": 'Data.ashx', 
        // ^ Change this ashx filename based on 
        //   the file you created above in #2  
    "aoColumns": [
        { "mDataProp": "column1" },
        { "mDataProp": "column2" },
        { "mDataProp": "column3" } ]
});

Datatable at server side - Stack Overflow

datatable datatables server-side
Rectangle 27 4

1) Yes it is common to use Ajax and Asp.net on the same website. I do it all the time(in fact if you turn off javascript on my sites they won't work too well as so much is AJAX). AJAX allows for requests to the server to be made without refreshing the page you still need a serverside language to do stuff with that request. You also need the load the page for the first time so asp.net controls still are needed and in fact if your using asp.net ajax then you can use update panels where you put controls into that automatically become ajax enabled.

2) I am not sure what you mean but Ajax is mostly javascript so it lives on the client side and sends requests to the server side.

Ok I skimmed most of the stuff in those chapters. AJAX server side is where most of the rendering is done on the server side. So the update panel is an ajax server side control. You drag it on to your webform throw some other server side controls into it and a button. If a user then clicks on that button in the update panel an ajax request is made to the server and you can grab all the stuff you need and use C# to change it. You never have to write one line of javascript code to make that happen.

Of course that has a price though for instance an update panel does not do a true ajax request because of the page life cycle. If you actually watch the code through the debugger you will notice it will go through the page life cycle but in the end will just rerender that update panel so there is a bit more over head then if you did it yourself.

Client side Ajax is basically Microsoft trying to make it easier for you to do javascript by trying to make it more like C# syntax and giving you built in methods. A problem is that alot of people throw the buzz word Ajax too often around and call stuff that should not be called Ajax when it should be just called javascript.

This seems to be the case with this client side ajax as most of what I seen in the client side ajax chapter is almost all javascript. Like in "Figure 33.8. Selecting a menu item." all it seems to be is your click on a choose then it displays the name of that button that is not really Ajax.

Ajax to me is when you actually make a server request to post or get some information with out the page refreshing(ie full post back). For example if you got a form of data that you want to send to the server to be saved in a database. If you would hit the save button and that form data would be sent to the server without the page refreshing then that would be an Ajax request.

Most of the stuff in the ajax tool kit is more javascript

For instance the calendar control to make it select different dates it is not doing any sort of request to the server since it is all javascript so why would it be ajax if it never posts to the server?

If you would take the value in the textbox that the calendar control puts the date in and post it to the server without refreshing the page that would be an Ajax request.

Finally I would not be too worried about asp.net webforms going anywhere anytime soon. I believe the guy who wrote that article about asp.net going to dye is the guy who made Ajax or was involved some how with the development of Ajax so he is probably biased.

Besides look its been 5 years now since he posted that and asp.net is stronger then ever. Ajax still needs a server to connect to, you still need to render the initial page load with either straight html or asp.net server controls.

1) Yes I think jquery is better the MS ajax for a couple reasons:

  • It uses less resources then drag and drop controls
  • It simplifies javascript alot as it makes it easier to use(such as selecting html controls,etc). So if I was using MS ajax I probably still be using jquery for the selectors it has so it is kinda redundant to use both unless you have a good reason too.

2) You really only need to learn jquery and not even javascript. I read a javascript book in like a day then jumped into jquery without even doing on exercise in the book and never did javascript before and I had no problem doing jquery. Of course if you got javascript experience it is a plus since sometimes you will be trying to find a jquery solution when javascript already has a method for what you want to do.

The only problem is that it can be a bit trickery to do ajax request using jquery when using asp.net webforms(asp.net mvc was designed with frameworks like jquery in mind so it is easier to do).

Are you implying that perhaps jquery could be too much of a hassle when used together with webforms and thus I should think of using Asp.Net Ajax instead?

No I am not implying that it is too much hassle for webforms was just stating the fact that it will be a bit more tricky in certain situations then ms ajax and jquery with say asp.net mvc.

asp.net webforms was not really made for a framework like jquery and has trouble dealing with it because of it's page life cycle gets in the way. MS ajax might have it's own set of challenges though too(like everything usually does). Jquery was made in mind of to try and work across all browsers since in javascript many times you would write something that worked in IE but did not work in any other browser and I am not sure if MS ajax client side version thought about this.

B) Little I read on ajax is that it also needs to call web services or some other technology that provides similar functionality to web services. If true, which technology do you use ( WCF or Asp.Net web services or )?

Yes this is true. This was the whole point many people including me where trying to make to prove that guy was wrong that asp.net was dying because of ajax, since you need something in the back end to make a call too.

However you can choose whatever you want. You can make a separate web service( can be a asp.net web service), you can have like static web service methods in your page load ( I never done this way) and the way I use to do it is by making a generic ajax handler.

You can't however just make a regular method in your page_load and try to call it as it has to go through the entire page life cycle.

I have not read these tutorials but these tutorials should show you the 3 different ways you can do an ajax request to an asp.net webservice, asp.net code behind page and asp.net generic handler.

C) Is Ajax a subsection of jquery? Thus, to understand Ajax, will I need to purchase only a book on jquery or will I also need to read a book with Ajax in its title

Ajax is just part of jquery and probably won't take you long to learn. If you buy a book about jquery there will probably be like 1 chapter on it. The only down side is all the jquery books I know of are all in php.

So if your just buying it to learn the ajax part probably not worth it since they will show an entire example of how to do it with php that might be slightly different then if you did it with asp.net( mostly just setting up the server side to accept the jquery calls- see the links that I posted above).

If you want to learn jquery selectors and stuff then it does matter if the one chapter is in php since it's all client side stuff expect for the ajax part( what is client side and server side).

It's not hard to really do the ajax stuff it just knowing what path you need to choose and more how to accept stuff on the server side and return stuff from the server side.

$.post("test.php", { name: "John", time: "2pm" },
   function(data){
     alert("Data Loaded: " + data);
   });

The above is basically all you need to do on jquery side to send some ajax stuff. The first parameter is the path where this request should go. In this case its some php file called test. The next parameter is the the actual data sent as a json result and finally the last line is the function call back line. When the ajax post request is done that line gets called and does the actions. Data is the returned stuff you sent back from the server.

So I would just go through the tutorials I posted and play around with the jquery selectors. Once you done that you can decide if you want to go with jquery or not. The last thing I wanted to point out about why I like jquery is the fact that if you learn the MS ajax stuff your basically stuck with asp.net( what I have no problem with since I love .Net) but with jquery you can easily take your code or those skills of jquery and use it with php, ruby or whatever else and all the client side jquery selectors won't change by switching a different language. The only thing that will be different is the ajax stuff and even that won't be 100% different as the jquery ajax client side could will be the same.

Well I don't know too much about MS ajax framework as I use jquery for all my Ajax needs with asp.net. It could be that the AJAX server side is like drag and drop controls that get rendered on the server side but to make it actually work there is tons of javascript code. I will look more into it. I only used the MS Ajax stuff once and that was like 3 years ago and some of the stuff they called AJAX is sometimes stuff I would not classify as AJAX. If you got a link to where you read this that would be helpful.

check my edit in the above post.

Well it's up to you I am sure MS stuff is good. For me it was sort of a life saver. When I was learning asp.net and C# I did not want to learn about javascript and ajax as it would be just to over whelming to learn all at once but at the same time I wanted to give my sites that functionality that javascript and ajax brought. So it was very helpful in the beginning for me. I don't use it anymore since I moved onto a javascript framework called jquery(MS has put their full support behind the people making this framework). It makes javascript so much easier to do, has ajax and tons of plugins...

That you won't need to make many things that you need as there are usually 10 versions of something that you want(for instance if you want a date picker or javascript tabs).

Is it Asp.Net or Ajax or can both technologies be used together when d...

asp.net ajax asp.net-ajax
Rectangle 27 17

If you want to find the control from code behind you have to use runat="server" attribute on control. And then you can use Control.FindControl.

<div class="tab-pane active" id="portlet_tab1" runat="server">

Control myControl1 = FindControl("portlet_tab1");
if(myControl1!=null)
{
    //do stuff
}

If you use runat server and your control is inside the ContentPlaceHolder you have to know the ctrl name would not be portlet_tab1 anymore. It will render with the ctrl00 format.

Something like: #ctl00_ContentPlaceHolderMain_portlet_tab1. You will have to modify name if you use jquery.

You can also do it using jQuery on client side without using the runat-server attribute:

<script type='text/javascript'>

    $("#portlet_tab1").removeClass("Active");

</script>

if i do it with jquery, do i need runat="server" attribute?

No you dont need. Jquery access the control directly from the client side. Perfect to manage css

Visual Studio should auto update the associated designer file with a declaration for myControl1 after adding runat="server", making an explicit one unnecessary.

c# - Find div tag from code behind - Stack Overflow

c# asp.net
Rectangle 27 1

Instead of trying to get the value from the server control in the static page method, have jQuery get the selected value and send it to your page method, like this:

$(document).ready(function() {
    var selectedMake = $('#<%= MAKE.ClientID %>' option:selected").text();

    var args = {
        theMake : selectedMake
    }

    $.ajax({
        type: "POST",
        url: "YourPageName.aspx/Select_Search",
        data: JSON.stringify(args),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            // Do something with result here
        }
    });
});

This requires a change to the static web method, in order to allow it to accept a parameter now, like this:

Now you do not have to attempt to find the value of the server control in a static method, because it was sent to the static method as a parameter.

  • The example above makes extensive use of jQuery, make sure you have a reference in your page or master page, if you are using them, to the jQuery script file
  • I am not sure what you are actually doing in your page method, because it is declared as returning a String, but it appears to trying to return a List, along with an unused Catch block, I deleted the unused Catch and Finally blocks and had it return the dtst object, feel free to correct this as needed.

The only option you have server-side to allow access to the value in the Static web method is to use Session cache to store the drop down's selected value when it is changed via the drop down's SelectedIndexChanged event, like this:

Sub Index_Changed(sender As Object, e As EventArgs)        
    Session("SelectedMakeValue") = ddlMake.SelectedItem.Value
End Sub

Now you must give the Static web method access to the Session cache, like this:

'Static or shared Web Method'
<WebMethod(EnableSession := True)> _
Public Shared Function Select_Search() As string
    Dim dtst As New DataTable()
    Dim List As New dsStockTableAdapters.newSTOCK_LISTTableAdapter()
    Dim theMake As String = HttpContext.Current.Session("SelectedMakeValue").ToString()
    dtst = List.GetData()
    Return dtst
End Function

Note: You must use the fully qualified name for the Session object, which is HttpContext.Current.Session; otherwise you will get errors.

hi @karl Anderson i know how to pass parameter values in Ajax but i need to do it in codebhind.. i just asked to the point question the shared method which i am using is very long which i updated now

Session

c# - Access Control value in static or shared Method in asp.net - Stac...

c# asp.net vb.net
Rectangle 27 1

Text in a label will not be sent to the server, you will need to use some sort of input control.

I'd suggest that you use a hidden control, and have your JQuery update both the label and the hidden input.

@Html.HiddenFor( x => x.TotalAmount)
<label id="total-amount">
     @Html.Encode(@Model.TotalAmount)
</label>

if (!$(this).is(':checked')) {
   var lblTotalAmount = $("#total-amount");
   var totalAmount = nationalPrice + recurPrice;
   lblTotalAmount.text(totalAmount.toFixed(2));

   var hiddenInput = $("#TotalAmount");
   hiddenInput.val(totalAmount);   
}

asp.net mvc 3 - JQuery and MVC POST - Stack Overflow

jquery asp.net-mvc-3
Rectangle 27 1

You can use jQuery and the Validation plugin to perform client side validation. This will work with both html tags and asp.net server controls. Phil Haack has a good sample project that will show you the basics.

This SO question has an in depth review of this approach as well.

Determine if page is valid in JavaScript - ASP.NET - Stack Overflow

asp.net javascript validation
Rectangle 27 1

You can use jQuery and the Validation plugin to perform client side validation. This will work with both html tags and asp.net server controls. Phil Haack has a good sample project that will show you the basics.

This SO question has an in depth review of this approach as well.

Determine if page is valid in JavaScript - ASP.NET - Stack Overflow

asp.net javascript validation
Rectangle 27 1

You can use jQuery and the Validation plugin to perform client side validation. This will work with both html tags and asp.net server controls. Phil Haack has a good sample project that will show you the basics.

This SO question has an in depth review of this approach as well.

Determine if page is valid in JavaScript - ASP.NET - Stack Overflow

asp.net javascript validation
Rectangle 27 4

Yes, this is possible. One way to do this using purely ASP.NET (which seems like what you're asking for) would be to keep a count of the TextBox controls that you have added (storing that value in the ViewState) and recreate the TextBox controls in the Page_Load event. Of course, nowadays most people would probably use Javascript or jQuery to handle this task client side, but I put together a quick example to demonstrate how it works with postbacks:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicControls.aspx.cs" Inherits="MyAspnetApp.DynamicControls" EnableViewState="true" %>
<!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"></head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnAddTextBox" runat="server" Text="Add" OnClick="btnAddTextBox_Click" />
        <asp:Button ID="btnWriteValues" runat="server" Text="Write" OnClick="btnWriteValues_Click" />
        <asp:PlaceHolder ID="phControls" runat="server" />
    </div>
    </form>
</body>
</html>
using System;
using System.Web.UI.WebControls;

namespace MyAspnetApp
{
    public partial class DynamicControls : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Recreate textbox controls
            if(Page.IsPostBack)
            {
                for (var i = 0; i < TextBoxCount; i++)
                    AddTextBox(i);
            }
        }

        private int TextBoxCount
        {
            get 
            {
                var count = ViewState["txtBoxCount"];
                return (count == null) ? 0 : (int) count;
            }
            set { ViewState["txtBoxCount"] = value; }
        }

        private void AddTextBox(int index)
        {
            var txt = new TextBox {ID = string.Concat("txtDynamic", index)};
            txt.Style.Add("display", "block");
            phControls.Controls.Add(txt);
        }

        protected void btnAddTextBox_Click(object sender, EventArgs e)
        {
            AddTextBox(TextBoxCount);
            TextBoxCount++;
        }

        protected void btnWriteValues_Click(object sender, EventArgs e)
        {
            foreach(var control in phControls.Controls)
            {
                var textBox = control as TextBox;
                if (textBox == null) continue;
                Response.Write(string.Concat(textBox.Text, "<br />"));
            }
        }
    }
}

Since you are recreating the controls on each postback, the values entered into the textboxes will be persisted across each postback. I added btnWriteValues_Click to quickly demonstrate how to read the values out of the textboxes.

EDIT I updated the example to add a Panel containing a TextBox and a Remove Button. The trick here is that the Remove button does not delete the container Panel, it merely makes it not Visible. This is done so that all of the control IDs remain the same, so the data entered stays with each TextBox. If we were to remove the TextBox entirely, the data after the TextBox that was removed would shift down one TextBox on the next postback (just to explain this a little more clearly, if we have txt1, txt2 and txt3, and we remove txt2, on the next postback we'll create two textboxes, txt1 and txt2, and the value that was in txt3 would be lost).

public partial class DynamicControls : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            for (var i = 0; i < TextBoxCount; i++)
                AddTextBox(i);
        }
    }

    protected void btnAddTextBox_Click(object sender, EventArgs e)
    {
        AddTextBox(TextBoxCount);
        TextBoxCount++;
    }

    protected void btnWriteValues_Click(object sender, EventArgs e)
    {
        foreach(var control in phControls.Controls)
        {
            var panel = control as Panel;
            if (panel == null || !panel.Visible) continue;
            foreach (var control2 in panel.Controls)
            {
                var textBox = control2 as TextBox;
                if (textBox == null) continue;
                Response.Write(string.Concat(textBox.Text, "<br />"));
            }
        }
    }

    private int TextBoxCount
    {
        get 
        {
            var count = ViewState["txtBoxCount"];
            return (count == null) ? 0 : (int) count;
        }
        set { ViewState["txtBoxCount"] = value; }
    }

    private void AddTextBox(int index)
    {
        var panel = new Panel();
        panel.Controls.Add(new TextBox {ID = string.Concat("txtDynamic", index)});
        var btn = new Button { Text="Remove" };
        btn.Click += btnRemove_Click;
        panel.Controls.Add(btn);
        phControls.Controls.Add(panel);
    }

    private void btnRemove_Click(object sender, EventArgs e)
    {
        var btnRemove = sender as Button;
        if (btnRemove == null) return;
        btnRemove.Parent.Visible = false;
    }
}

thanks a lot dude!! this is what I was looking for!

What about if I want to delete the dynamic textbox? I insert a button and assign an event to it whenever a textbox is created. Actually, on the first click the textbox is being deleted succesfully, but then some errors may occur (not exceptions but for instance the value of the textbook is not saved on click). Is there an easy way to delete the specified textbox?

haha it was so easy :) I was keeping to remove the panel, thanks alot again :) it works fully now :)

c# - Persistent dynamic control in ASP.Net - Stack Overflow

c# asp.net dynamic controls persistent
Rectangle 27 3

As others have mentioned, you can pass a class selector to jQuery, but that is a bit messy. I prefer to use the jQuery attribute ends with selector. Given that a generated ID is a flattened hierarchy of controls, you can use the "ends with" selector to find your element.

<input runat="server" id="txtText" />

When rendered, the generated ID becomes something like this (if within a masterpage's content place holder):

<input id="ctl00_contentplaceholder_txtText" />
$("input[id$='txtText']")

Take caution when using this within a repeater.

javascript - Getting ID from asp.net runat server in jQuery - Stack Ov...

javascript jquery asp.net runatserver
Rectangle 27 3

As others have mentioned, you can pass a class selector to jQuery, but that is a bit messy. I prefer to use the jQuery attribute ends with selector. Given that a generated ID is a flattened hierarchy of controls, you can use the "ends with" selector to find your element.

<input runat="server" id="txtText" />

When rendered, the generated ID becomes something like this (if within a masterpage's content place holder):

<input id="ctl00_contentplaceholder_txtText" />
$("input[id$='txtText']")

Take caution when using this within a repeater.

javascript - Getting ID from asp.net runat server in jQuery - Stack Ov...

javascript jquery asp.net runatserver
Rectangle 27 2

I figured this out. To partial postback to the server via an UpdatePanel without using hidden controls, do this with jQuery:

<script type="text/javascript">
    $(document).ready(function () {
        __doPostBack('<%=UpdatePanel1.ClientID %>');
    });
</script>

This will perform a partial postback to the server against the UpdatePanel with the ID UpdatePanel1 as soon as the HTML DOM is ready. You can then use the ASP.NET page life cycle to hook into whatever event is appropriate for you. I hooked into the load event of the update panel:

protected void UpdatePanel1_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack && Session["InitializedKey"] == null)
    {
        Session["InitializedKey"] = true;
        // do your initialization stuff here
    }
}

The code above will only run if the page is posting back and the session variable is set. Now you have to clear the session variable when the user refreshes the page since the intent here is to run this code on the first postback and only the first postback. So clear the session variable in the Page_Load:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
        Session[initializedKey] = null;
}

And if you want to show a progress indicator while the page is in partial postback, do this javascript:

<script type="text/javascript">
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_beginRequest(BeginRequestHandler);
    prm.add_endRequest(EndRequestHandler);
    function BeginRequestHandler(sender, args) {
        if (args._postBackElement.id == '<%=UpdatePanel1.ClientID %>') {
            $get('Progress').className = 'Progress';
        }
    }
    function EndRequestHandler(sender, args) {
        if (sender._postBackSettings.sourceElement.id == '<%=UpdatePanel1.ClientID %>') {
            $get('Progress').className = 'Hidden';
        }
    }
</script>

This requires a div tag with the id 'Progress' and whatever you want to show for progress within that div. You also need some css to set the display and visible styles on the div tag in classes named Hidden and Progress. Don't forget to perform error handling on partial postbacks!

asp.net - How do I perform a partial post back after the page loads on...

asp.net ajax asp.net-ajax
Rectangle 27 5

If you are looking for server side validation you can use something like below using

ModelState.AddModelError("", "Name and Url are required fields.");
@Html.ValidationSummary(false)
[HttpPost]
public ActionResult InsertRssFeed(string Name, string Url)
{

    if (String.IsNullOrEmpty(Name.Trim()) || String.IsNullOrEmpty(Url.Trim()))
    {
        ModelState.AddModelError("", "Name and URL are required fields.");
        return View();
    }

    var rssFeed = new RssFeed();
        rssFeed.Name = Name;
        rssFeed.Url = Url;

    using (AuthenticationManager authenticationManager = new AuthenticationManager(User))
    {
        string userSid = authenticationManager.GetUserClaim(SystemClaims.ClaimTypes.PrimarySid);
        string userUPN = authenticationManager.GetUserClaim(SystemClaims.ClaimTypes.Upn);

        rssFeedService.CreateRssFeed(rssFeed);
    }

    return RedirectToAction("ReadAllRssFeeds", "Rss");
}

If you are looking for only client side validation, then you have to use client side validation library like Jquery.

your razor should be like this.

@using (Html.BeginForm("InsertRssFeed", "Rss", FormMethod.Post, new { @id = "insertForm", @name = "insertForm" }))
{
    @Html.ValidationSummary(false)

        <div class="form-group">
            <label class="col-sm-2 control-label"> Name:</label>
            <div class="col-sm-10">
                <div class="controls">
                    @Html.Editor("Name", new { htmlAttributes = new { @class = "form-control", @id = "add_rssFeed_name" } })
                </div>
            </div>
        </div>

            <div class="form-group">
                <label class="col-sm-2 control-label"> URL:</label>
                <div class="col-sm-10">
                    <div class="controls">
                        @Html.Editor("Url", new { htmlAttributes = new { @class = "form-control", @id = "add_rssFeed_Url" } })
                    </div>
                </div>
            </div>

        </div>
    </div>
        <!-- ok and cancel buttons. they use two css classes.  button-styleCancel is grey button and button-styleOK is normal orange button -->
    <div class="modal-footer">
        <button type="button" class="button-styleCancel" data-dismiss="modal">Close</button>
        <button type="submit" class="button-styleOK" id="submitRssFeed">Save RSS Feed</button>
    </div>
}

thanks for answer. Exactly, I am trying to achieve server side validation. On client side I have validation with jquery.Anyway, if I turn off that ckient side, jquery validation, and put this code you provided, its still not working as it should. I am not getting message if I leave some of the fields empty.

Yes, I have added @Html.ValidationSummary(false) to razor view, right below <div class="form-group"> of @Html.Editor("Url"...) part.

I have added code which I suppose you are using in razor. Are you correctly referencing required scripts? can you check the whats render when you trying to validate putting debug points on action and check are you correctly return to the view with model error on it.

Thanks for help. I am obviously doing something wrong, will post when I find whats the problem.

c# - ASP .NET MVC Form fields Validation (without model) - Stack Overf...

c# asp.net asp.net-mvc asp.net-mvc-4 validation
Rectangle 27 4

Since you're using jQuery and you control the server-side, change your server code so that it looks for the callback parameter. The value of this parameter will be the name of the callback function that the client-side code is expecting. Then instead of returning the bare JSON, return it in the form: callbackName(rawJson).

String callbackName = request.getParameter("callback");

// ... your JSON code 

if (callbackName != null)
{
    // JSONP wrapping:
    response.getWriter().write(callbackName +
                               "(" + stringWriter.toString() + ")");
    System.out.println(callbackName + "(" + stringWriter.toString() + ")");
}
else
{
    response.getWriter().write(stringWriter.toString());
    System.out.println(stringWriter.toString());
}

response.getWriter().close();

Then on the client-side, continue to use jQuery.getJSON, but append a ?callback=? query parameter to your URL, or instead use jQuery.ajax for your call, and use the dataType: jsonp setting.

java - How to convert from JSON to JSONP? - Stack Overflow

java jquery json jsonp
Rectangle 27 3

It must be runat=server because user controls are special controls processed by the .net engine on server side. An ASP.NET User Control doesn't make any sense on client side, it needs a "translation" before be sent to client.

In order to respond to selected index change event first you'll need to assign an id or a css class to the select so you can identify it more accurately trough a jQuery selector (assuming you want to use jQuery since you added it to question tags).

Something like this should do the trick

<select id="mySelect">
    <option disabled selected>Select Options</option>
    <option>
        option 1
    </option>
    <option>
        option 2
    </option>
</select>
// Shorthand for $( document ).ready()
$(function() {
    $('#mySelect').change(function(){
         // your logic when index changed here
    });
});

This answer is the way to go. The page can know about the contents of the control, because it's instantiating the control, but avoid putting any code in the control that makes assumptions about the page it's instantiated on. That's a recipe for future headaches.

c# - ASCX result to call javascript found in ASPX - Stack Overflow

javascript c# jquery asp.net
Rectangle 27 4

I don't know if this helps, but I set up my autocomplete a bit differently. I use the source property which allows me to control the call back to jQuery. My ajax call returns items in the form of [{"id":1, "label": "Annie Hall",.....]. You could modify the results of the Ajax call however you want depending on how the data comes back from the server. Here is the code I use to call it.

$("#movieSearch").autocomplete({
            source: function(req, res){
                $.getJSON(
                    "search.aspx",
                    {term : req.term},
                    function(data){
                        res(data);//you can also modify your results before you call res()
                    }
                );
            }
);

One thing in your example which troubles me is the variable results, which seems to me to be a global variable. And we all know (in the words of Douglas Crockford) that global variable are evil.

Thanks for your reply. As I have understood it, if you use the JSON in source: then it must return the data with "label": in the JSON? Currently I'm using Django, and it outputs "fields" - so I'll have to change that, but thats another problem :) Regarding the global variable: Would it be better to put the results = [] inside the getJSON?

jQuery UI autocomplete - results not shown when input does not match r...

jquery jquery-ui autocomplete jquery-autocomplete jquery-ui-autocomplete
Rectangle 27 1

The success option of the .validate() method is used for controlling the message element when validation passes. By default, the error message is hidden when validation passes. When using success, you can modify this behavior and show an icon, message, etc. when validation passes. However, this option does not retrieve messages from your server.

jQuery Validate is client-side code, and there is only one built-in method that will take a response from the server and that is the remote method. However, the issue here is that you can only pass a true to pass validation, a false to fail validation... and if you pass a string, it's converted into an error message and validation fails.

there is no built-in method for doing what you want

success
.ajax()

EDIT in response to OP:

but how do I define a success property here in remote and pass that success message to the validation messsage?

You can only use the success option to properly manipulate the error element. However, I don't think you'll be able to achieve the stated objective since there does not seem to be a way to pass the field's value into the success option. Otherwise, you could use .ajax() within success to retrieve your message.

and then change the color to green instead of red?

This is done automatically by defining your CSS properties for the valid and error classes. You can also apply custom classes using .addClass() within the success option.

IMO, your entire goal cannot be achieved using the jQuery Validate plugin. However, you should thoroughly review the documentation to be sure for yourself.

I think validate sets it to false if there is a string in the JSon response?

Yes, exactly as already stated in my answer. If the server response is anything other than true, the validation is set to fail.

won't the remote call in validate take a success property that I can use to pass a message back to the client side? Then couldn't I just display it in the validation message and color it green or something?

@user1186050, If the remote call gets anything other than "true", the field is flagged as "invalid".

what I want to show is the city, right. If I pass in a zipcode and a city is found I want to display the city in the validation message ex. "you found city San Francisco!", this would be after passing in "94102", other wise the error message is displayed saying something like "city not found"

@user1186050, as explained, 1. the plugin does not typically show messages on success. The success option is a way to force it to show messages. 2. the plugin does not typically communicate with the server except for the remote method.

c# - Showing a success validation message in ASP.Net MVC from server s...

c# jquery asp.net-mvc jquery-validate unobtrusive-validation
Rectangle 27 2

Make your checkbox a server-side control that uses the view state by adding runat="server". It will then maintain its value across post backs.

<input id="chkBoxAll" type="checkbox" onclick="checkAllBoxes()" runat="server"/>

And change your JavaScript to select the id that ends in chkBoxAll. I use jQuery in the example below:

//this is the checkbox in the header template
var mainChkBox = $('input[id$="chkBoxAll"]');

However, if you sort your gridview rows or use paging, you will likely come across less friendly behavior.

I get this... error CS0103: The name 'chkBoxAll' does not exist in the current context

<%= chkBoxAll.ClientID %>
ClientID

oh shoot.. yea just a minute

i keep getting the same error: error CS0103: The name 'chkBoxAll' does not exist in the current context

c# - SelectAll in gridview using javascript on postback issue - Stack ...

c# javascript asp.net gridview checkbox