[英]I have Button and TextBox in View of ASP.NET MVC - how to send value of Button to TextBox after Click on this Button?
我在ASP.NET MVC View
中有Button和TextBox
。 现在,如何在单击此按钮后将一些值(例如, string x="1";
)的Button发送到TextBox? 我有这样的值显示在这样的URL地址中: /local:xxxxx/Calculator?TextBox=&Command=1
在单击具有值1的Button之后,但是我不知道如何将该值发送到TextBox并转换为int并放入一些int变量。 我的视图如下所示:
<input type="text" name="TextBox" value=""/>
<table>
<tr>
<td><button type="submit" name="Command" value="7">7</button></td>
</tr>
我的模型如下所示:
public class CModel
{
public string Command { get; set; }
public string TextBox { get; set; }
}
和控制器:
[HttpGet]
public ActionResult Index()
{
CModel model = new CModel();
return View(model);
}
[HttpPost]
public ActionResult Index(CModel model)
{
if (model.Command == "1")
{
//do this and this
}
else if(model.Command == "2")
{
//do this and this
}
else if....{}
return View(model);
}
有什么方法可以获取此值“ 1”并发送到TextBox,然后发送到int类型的某个变量以进行保存? 怎么做?
您正在混淆太多东西。
首先,如果您要做的只是在按钮单击上设置文本框的文本,只需使用javascript即
假设您的按钮是这样的:
<input type="button" id="btnSetText" value="set Text" onclick="setText" />
那么您的js脚本应该是:
<script>
function setText(){
document.getElementById('txtBoxId').value = 'watever';
}
</script>
现在,如果要向给定控制器中的actionmethod发送值,则可以执行以下操作:
<script>
window.href.location ='/ControllerName/ActionMethod?value=' + 1;
</script>
ActionMethod是这样的:
public ActionResult ActionMethod(string value)
{
//process value
}
现在,如果您只是想访问保留在表单上的所有控件值,我建议您使用@Html.BeginForm
并提供适当的操作。 因此,当您按下保存在其中的“提交”按钮时,它将引发该操作中指定的控制器,以及@Html
中的所有@Html
控件,即
@using (Html.BeginForm())
{
@Html.ValidationSummary(true, "Login failed. Check your login details.");
<div>
<fieldset>
<legend>Login</legend>
<div class="editor-label">
@Html.LabelFor(u => u.UserName)
</div>
<div class="editor-field">
@Html.TextBoxFor(u => u.UserName)
@Html.ValidationMessageFor(u => u.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(u => u.Password)
</div>
<div class="editor-field">
@Html.PasswordFor(u => u.Password)
@Html.ValidationMessageFor(u => u.Password)
</div>
<div class="editor-label">
@Html.CheckBoxFor(u => u.RememberMe)
@Html.LabelFor(u => u.RememberMe)
</div>
<input type="submit" value="Log In" />
</fieldset>
</div>
}
并且您的ActionMethod将类似于:
[HttpPost]
public ActionResult Login(Models.User user)
{
if (ModelState.IsValid)
{
if (user.IsValid(user.UserName, user.Password))
{
FormsAuthentication.SetAuthCookie(user.UserName, user.RememberMe);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Login data is incorrect!");
}
}
return View(user);
}
//this takes request parameters only from the query string
Request.QueryString["Command"];
在您的情况下,上述方法将起作用。 您可以将以上代码放入.cs页的Page Load事件中。
//this one works for bot - form and query string
Request["Command"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.