简体   繁体   中英

Should I use a C# Event / Postback, or Javascript for something simple?

For the sake of argument, I have a DropDownList, with a variable number of items in. Let's say they come from an ObjectDataSource. I also have a TextBox, which I want to contain that value. Bear with me here.

EG

<asp:DropDownList runat="server" ID="ddlOptions">
    <asp:ListItem Text="Option 1" Value="Value1"></asp:ListItem>
    <asp:ListItem Text="Option 2" Value="Value2"></asp:ListItem>
    <asp:ListItem Text="Option 3" Value="Value3"></asp:ListItem>
</asp:DropDownList>

<asp:TextBox runat="server" ID="txtOptionValue"></asp:TextBox>

My question is - should I use a Postback to set the value, or some Javascript? I can either use the SelectedIndexChanged event of the DropDownList, or I can hook it up using some jQuery .change(func...) magic.

I'm not asking how to do this, but which would be the preferred method ? Personally, I think using jQuery looks cleaner to the end-user, but using a postback is more of a 'standard' way of doing things? Is there anything I'm missing?

JAVASCRIPT is meant to be used whatever you can do on client side.

The thing that you are doing is clearly possible to be done using jQuery so there is no need to hit the server just to set the value.

Try to reduce server hit as many as possible. This should be the motto of developers

是的,您是对的,jQuery是最好的选择,但是这完全取决于您的要求,如果页面没有任何回发,那么您可以选择JQuery,否则最好选择回发。

You should probably think about the overall architecture and user experience requirements.

Lets say your clients want a smooth experience, something like a single page app. Then yes, start throwing in all the javascript and jquery you can to achieve as this, with something like WebAPI instead of asp.net. Check out ASP.NET SPA .

Lets say your client isn't requiring anything fancy. Why go through all the trouble of adding javascript when you can quickly achieve it by using standard asp.net callbacks.

It looks like you are using ASP.net. I would stick with normal out-of-the-box asp.net unless the requirements say otherwise. No sense in throwing in all these other libraries or dependencies if if this is the only place you'll use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM