0

I am new to ASP.NET Core MVC. I want to move the text string from controllers to views. Here is my controller.

public class CalculatorController : Controller
{
    public string text= "";

    public IActionResult Index()
    {
        ViewData["Text"] = text;
        return View();
    }

    public IActionResult Button1_Click(string button)
    {
        text += button;
        return RedirectToAction("Index");
    }

    public IActionResult Button2_Click(string button)
    {
        text = text + button;
        return RedirectToAction("Index");
    }
}

In the controller, I make a public string text, in which the button value be stored when button1_Click, it stores its value and shows in the input textbox and when Button2_Click it stores and show both the values of button1 and button2 in the input textbox.

The input textbox markup is here:

<input type="text" asp-controller="Calculator" asp-action="Index"  
       value="@ViewBag.Text" class="form-control" />

But this code does not work well.

2
  • I am not sure what this MVC does. For example, what would be shown if I click Button1 twice? Commented Dec 7, 2021 at 6:37
  • You can set break point at return xxx lines, and you'll find the ViewData["Text"] doesn't keep the value from each other, so you can only set the complete value. Commented Dec 7, 2021 at 6:54

2 Answers 2

1

You need to take to account that when you execute action method public IActionResult Index(), there is one instance of your controller class. But after posting a new text value from the view a new instance of your controller class will be created. To see this I added printing of the controller class hash code: Debug.WriteLine("[HttpGet] This is: " + this.GetHashCode());.

This is why this operator text += button; in your code will not work as you expected.

To persist the text between request, in this example, the TempData is used.

Code fragment in controller:

public IActionResult Index()
{   
    System.Diagnostics.Debug.WriteLine("[HttpGet] This is: " + this.GetHashCode());
    TempData["TextData"] = "Hello World!";
    return View();
}

[HttpPost]
public IActionResult Index(string data)
{
    System.Diagnostics.Debug.WriteLine("[HttpPost] This is: " + this.GetHashCode());
 
    TempData["TextData"] += data;
    ModelState.Remove("data"); // The context clean up 
    return View("Index");
}

The view Index.cshtml:

@{
    var data = TempData["TextData"];   
}

@using (Html.BeginForm("Index", "Calculator"))
{
    <input type="text" asp-for="@data" />
    TempData.Keep("TextData"); // To preserve the data at the end of the request
}

See the following post for additional information: Session and state management in ASP.NET Core

Sign up to request clarification or add additional context in comments.

2 Comments

Ooh Thanks!! But when I click the button1 than in Button1_Click text string value be 1,But after RedirectToAction("Index"), than the text string value be Null in index action method.
@Shahriyar Rahim: See the updated answer. Thanks.
0

In my opinion, if you only need to append the text value of the button to your input box, you even not need to make a request to your backend controller, unless you need to do some other operations. If so, I recommend you to use ajax here to only send the button text string to your controller, and then you can do some thing in the success call back function like this:

public IActionResult Index()
{
    ViewData["Text"] = "asdf";
    return View();
}

public string Button1(string button)
{
    // do your own business here
    return text;
}

public string Button2(string button)
{
    // do your own business here
    return text;
}

And in the cshtml file,

<input type="text" id="input1" value="@ViewBag.Text " />
<a href="#" id="ccc">ccc</a>
<a href="#" id="ddd">ddd</a>

<script>
    $("#ccc").click(function () {
        $.ajax({
            url: "https://localhost:44372/home/Button1",
            type: "get",
            data: {
                button: "ccc"
            },
            success: function (data) {
                $("#input1").val($("#input1").val() + data);
            }
        });
    });

    $("#ddd").click(function () {
        $.ajax({
            url: "https://localhost:44372/home/Button1",
            type: "get",
            data: {
                button: "ddd"
            },
            success: function (data) {
                $("#input1").val($("#input1").val() + data);
            }
        });
    });
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.