MVC 5按钮单击事件,用于更新同一表单上的标签

时间:2014-06-01 12:09:58

标签: asp.net-mvc asp.net-mvc-5

使用MVC 5,是否可以在同一页面上更新标签的按钮点击事件?

例如,如果我有结构

@using (Html.BeginForm()) {
    <fieldset>
        <legend>Form</legend>
        <p>
            @Html.TextBox("textbox1")
        </p>
        <p>
            @Html.Label("label1")
        </p>
        <p>
            <input type="submit" value="Submit" />
        </p>
    </fieldset>
}

单击Submit按钮获取textbox1的值,根据单击提交按钮时调用的函数对其进行修改,然后将标签的值更新为导致?

假设我的控制器被调用TestController.cs,这一切都在Index页面上完成

我注意到有些suggestions包括使用AJAX(对我而言)

3 个答案:

答案 0 :(得分:2)

您需要做的就是将标签的值作为操作结果的一部分传递回去,例如

<强>控制器

public class TestController : Controller
{
    public ActionResult Index(string label)
    {
        // pass label value into view
        return View("Index", label ?? "");
    }

    [HttpPost]
    public ActionResult Index(string textValue)
    {
        // do something with textValue
        // redirect to our Index action passing the new label value
        return RedirectToAction("Index", textValue);
    }
}

查看

@model string

@using (Html.BeginForm()) {
    <fieldset>
    <legend>Form</legend>
    <p>
        @Html.TextBox("textbox1")
    </p>
    <p>
        @Html.Label("label", Model)
    </p>
    <p>
        <input type="submit" value="Submit" />
    </p>
    </fieldset>
}

这种方法的好处在于它遵循Post/Redirect/Get模式,因此如果您刷新页面,它将不会再尝试重新提交表单。

答案 1 :(得分:1)

试试这个:

你的cshtml代码:

@using (Html.BeginForm()) {
    <fieldset>
        <legend>Form</legend>
        <p>
            <input type="text" id="textbox" name="textbox"/>
        </p>
        <p>
           <lable id ="lable"></lable>
        </p>
        <p>
            <input type="button" id="button" value="Submit" />
        </p>
    </fieldset>
}

jquery:

<script type="text/javascript">
$(document).ready(function(){
    $("#button").click(function(){
document.getElementById("lable").innerHTML = $("#textbox").val();
    });
});
</script>

演示:

http://jsfiddle.net/mgGj6/2/

希望它有效......!

感谢。

答案 2 :(得分:0)

您也可以使用

使用Ajax
@Ajax.BeginForm();

帮手。对最终用户来说会更舒服。