johnnie
johnnie

Reputation: 2057

How to set code behind properties in javascript

Is it possible to set a property of the code behind using javascript?

I have the following:

private string dateFormat;
public string DateFormat
{
    get
    {
        return dateFormat;
    }
    set
    {
        dateFormat = value;
    }
}

and want to set it like this: '<%=DateFormat%>' = "dd-mm-YYYY"

But when I run this and add a debbugger it comes out like this: '' = "dd-mm-YYYY".

Upvotes: 0

Views: 2418

Answers (2)

Onur Topal
Onur Topal

Reputation: 3061

Try without quotes:

var <%=DateFormat%> = "dd-mm-YYYY";

but in your case the property does not have a value so you should check if it is set.

Upvotes: 2

Rawling
Rawling

Reputation: 50154

You can't do this directly; you need to use an ASP.NET hidden field which will then return the value to your code on a postback, and persist it across multiple postbacks.

The C# would be like

public string DateFormat
{
    get
    {
        return DateFormatField.Value;
    }
    set
    {
        DateFormatField.Value = value;
    }
}

The JavaScript to set it would be something like

document.getElementById('<%=DateFormatField.ClientID%>').value = 'dd-mm-YYYY';

Upvotes: 1

Related Questions