user2043533
user2043533

Reputation: 751

Label in gridview changes but change does not postback

I have a gridview with a label, along with some JavaScript and jQuery to make the label editable.

However, when I postback and debug in my code behind I do not see the change.

How can I make it so I can get the change on the server?

<asp:GridView ID="gvGroups" runat="server" AutoGenerateColumns="False"
 CssClass="table table-hover table-striped" GridLines="None" >
    <Columns>
        <asp:TemplateField HeaderText="Name" SortExpression="GroupDescription">
            <ItemTemplate>
                <asp:Label ID="lblName" CssClass="edit" runat="server" Text='<%# Eval("GroupDescription") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

function makeLabelsEditable() {

    $(".edit").focusout(function () {
        setLabel(this);
    });

    $(".edit").click(function () {
        editLabel(this);
    });
}

function editLabel(source) {
    source.innerHTML = '<input type="text" maxlength="40" value="' + source.innerHTML + '"/>';
    $(source).unbind('click');
    source.children[0].focus()
}
function setLabel(source) {    
    if (source.children[0].value != '') {
        $(source).click(function () {
            editLabel(this);
        });
        source.innerHTML = source.children[0].value;
    }    
}

Upvotes: 4

Views: 1741

Answers (3)

NaveenBhat
NaveenBhat

Reputation: 3328

The ViewState will not be generated for the label in client side, since it is intended to be read only. Hence, you are getting same value in the post-back which you set in the server earlier.

The easiest workaround what I can think of is:

  • Place a TextBox instead of label.
  • Apply a css class to it so that it look like a Label.
  • On click of the TextBox, remove the css.

You can apply the css back whenever you want to give the label look.

Upvotes: 0

algreat
algreat

Reputation: 9012

You can't make changes on the server in this way. You just change html on the client side

Upvotes: 0

Kelsey
Kelsey

Reputation: 47766

Label will not postback to the server. They are intended to be readonly and render as a span. If you want it to post back the easiest thing to do is make a Hidden control with the same value and when you do you code to allow editting to a label, you make sure to write the editted value to the Hidden. The Hidden will be posted back to the server and then you can read the value.

You are swapping in a 'dynamic' TextBox so the server has no clue about the input control you made. You could read the raw posted params to get the value probably but it would be just easier to have a static control that you can write to and know it will have the value you need.

Upvotes: 1

Related Questions