使用C#设置HTML输入文本框的显示文本 [英] Set HTML input textbox's display text using C#

查看:73
本文介绍了使用C#设置HTML输入文本框的显示文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的ASPX页面中有一个HTML输入框,如下所示

I have a HTML input box in my ASPX page like below

<input id="txtID" runat="Server" type="text" />

现在我有一些用C#代码编写的代码可以计算一个值,并且希望该值显示在上面的文本框中.

Now I have some code written in C# codebehind which calculate a value and I want that value to be displayed in the above TextBox.

我已经尝试过

txtID.Value = Number.ToString();

HtmlGenericControl ct = new HtmlGenericControl();
ct.InnerHTML = Number.ToString();
txtID.Controls.Add(ct);

,但是以上两种方法似乎都无法设置文本框的显示文本.

but both of the above does not seems to set the display text of the textbox.

任何人都可以帮助我弄清楚如何完成它.我不能使用

Can anyone help me figure out as to how do I get it done. I cannot use

<asp:TextBox />

编辑(有正确答案):我最初尝试做的方法是正确的,即.

EDIT (WITH CORRECT ANSWER): The way I was originally trying to do was correct i.e.

txtID.Value = Number.ToString();

罪魁祸首是占位符插件,该插件被调用并正在删除TextBox中的值.希望这将对像我这样困在如此愚蠢的地方的很多人有所帮助.

The culprit was Placeholder Plugin which was getting called and was erasing the values from the TextBox. Hope this will help a lot of people like me who get stuck at such silly places.

推荐答案

您可以通过在PageLoad或PageInit上注入Javascript来更改控件的值.只需说 GetValueDummy()方法是您计算值的方法,并且您正在使用jQuery.

You can change value of control by injecting Javascript on PageLoad or PageInit. Just say GetValueDummy() method is your method to calculate a value and you are using jQuery.

您需要在Page.Load处理程序中的页面上注入JavaScript.

You need to inject a javascript to page in Page.Load handler.

protected void Page_Load(object sender, EventArgs e)
{
    var script = "$('#txt').val('" + GetValueDummy() + "');";
    ClientScript.RegisterStartupScript(typeof(string), "textvaluesetter", script, true);
}

在此代码中,txt是您输入的ID.

In this code, txt is id of your input.

如果您不使用jQuery,只需将脚本变量的值替换为

If you are not using jQuery just replace value of script variable to

var script = "document.getElementById('txt').value = '" + GetValueDummy() + "';";

在某些时候,您的页面将被完全渲染并准备发送给客户端.因此,您不能直接从c#对其进行修改.您可以在此处了解有关页面生命周期的更多信息: http://msdn.microsoft.com/en-us/library/ms178472.aspx

After some point your page will be fully rendered and ready to send to client. So you cant directly modify it from c#. You can read more about page life time here: http://msdn.microsoft.com/en-us/library/ms178472.aspx

这篇关于使用C#设置HTML输入文本框的显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆