MVC 5 button click event that updates a label on t

2019-07-26 04:54发布

Using MVC 5, is it possible to have a button click event that updates a label on the same page?

For example, if I have a structure

@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>
}

Clicking the Submit button grabs the textbox1's value, modifies it according to the function that gets called when the submit button is clicked and then update the value of the label as the result?

Assuming my controller is called TestController.cs and this is all done on the Index page

I noticed some suggestions include using AJAX (new to me)

3条回答
闹够了就滚
2楼-- · 2019-07-26 05:41

Try this :

your cshtml code :

@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>

Demo :

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

Hopefully it works...!

Thanks.

查看更多
小情绪 Triste *
3楼-- · 2019-07-26 05:43

You don't necessarily need to use AJAX for this. All you need to do is pass the value of your label back down as part of your action result e.g.

Controller

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);
    }
}

View

@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>
}

The benefit of this approach is it follows the Post/Redirect/Get pattern so if you refreshed the page it wouldn't try to re-submit the form again.

查看更多
对你真心纯属浪费
4楼-- · 2019-07-26 05:51

You can also do it with Ajax by using

@Ajax.BeginForm();

helper. It would be more comfortable for end user.

查看更多
登录 后发表回答