0

If I have this in my View:

@using (Html.BeginForm("Sum","Student"))
{
<p>
    Number1:
    @Html.TextBox("num1")
</p>
<P>
    Number2:
    @Html.TextBox("num2")
</P>
<input type="submit" value="Calculate"/>   
}

And this in my controller:

public void Sum(FormCollection values)
{
    var num11 = Convert.ToInt32(values["num1"]);
    var num21 = Convert.ToInt32(values["num2"]);
    int result = num11 + num21;  
    //How return result back to view and show it in a textbox      
}

How can I return the result back to the view and show it in a textbox?

Edit: I tried the following code as suggested but it then redirect me to another view without any result. I want to show the result in the same view that I send the data to the sum method:

public void Sum(FormCollection values)
{
     ....
     ViewBag.result = result;
}

And:

....
 <input type="submit" value="Calculate"/>
    string str = (string)ViewBag.Res;
    @Html.TextBox("Result",str)

3 Answers3

1

I would suggest you to use form-model instead of just named strings. It will allow you to do much more in much more beautiful way.

Views/Test/Index.cshtml

@model MyForm
@using (Html.BeginForm("Index", "Test"))
{
    <div>@Html.TextBoxFor(m => m.Num1)</div>
    <div>@Html.TextBoxFor(m => m.Num2)</div>
    <div>@Html.TextBoxFor(m => m.Result)</div>
    <input type="submit" value="Calculate" />
}

Myform.cs

public class MyForm
{
    public int Num1 { get; set; }
    public int Num2 { get; set; }
    public long Result => Num1 + Num2;
}

TestController.cs

public class TestController : Controller
{
    [HttpGet]
    public ActionResult()
    {
        return View(new MyForm());
    }

    [HttpPost]
    public ActionResult Index(MyForm form)
    {
        return View(form);
    }
}

UPDATED

Looks like we're talking about AJAX requesting here. Although i consider using AjaxHelper at MVC a bad practice (in a large projects with hierarchycal structure), in this case it might work just fine.

@using (Ajax.BeginForm("Calculate", "Test", new AjaxOptions
{
    HttpMethod = "GET",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "Result"
}))
{
    <div>@Html.TextBox("num1")</div>
    <div>@Html.TextBox("num2")</div>
    <div id="Result"></div>
    <input type="submit" value="Calculate" />
}

and the method

public ActionResult Calculate(FormCollection values)
{
    var num1 = Convert.ToInt32(values["num1"]);
    var num2 = Convert.ToInt32(values["num2"]);
    return Content(num1 + num2);
}

Don't forget to reference the js

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
Vladislav Qulin
  • 1,872
  • 1
  • 17
  • 20
  • Thanks. I know how can I do this with form-model. But I just want to know how can I do this by using named strings and FormCollection. –  Sep 08 '16 at 09:15
  • @user5032790 at some point its good to know how it works, sure, but the code quality in that case is a wack. – Vladislav Qulin Sep 08 '16 at 09:17
  • This is just for learning purpose. Please tell me how can I do that? –  Sep 08 '16 at 09:18
  • Thanks again. It seems a good way. But it show the result in a new page I want to show the result in the same view as I sent the data? –  Sep 08 '16 at 09:42
  • @user5032790, no, it does not, it sends the ajax request. You should just reference Microsoft.Ajax.js, jQuery.js and jquery.unobtrusive.ajax.js as scripts. Or you can just write the ajax call yourself to the form-generated-url. – Vladislav Qulin Sep 08 '16 at 09:46
  • Ok. I almost done it but please show me how can I reference the Microsoft.Ajax.js, jQuery.js and jquery.unobtrusive.ajax.js as scripts as you said because when I referenced you code it still show it in new page. Please give me a valid paths. –  Sep 08 '16 at 09:53
  • Give me online path please. –  Sep 08 '16 at 09:54
  • @user5032790 https://www.nuget.org/packages/Microsoft.jQuery.Unobtrusive.Ajax/ there you go. Add `` at the end of the view. – Vladislav Qulin Sep 08 '16 at 10:14
0
public ActionResult Sum(FormCollection values)
{
    var num11 = Convert.ToInt32(values["num1"]);
    var num21 = Convert.ToInt32(values["num2"]);
    int result = num11 + num21;
    ViewBag.result =result; 
    //How return result back to view and show it in a textbox

     return View();      
}

And use this ViewBag.result on your view page:

@Html.TextBox("result ", (string)ViewBag.result) 
Divyang Desai
  • 7,483
  • 13
  • 50
  • 76
  • Thanks. Please show an example of how can I use ViewBag.result in view? –  Sep 08 '16 at 09:03
  • Which control you would like to display for the result? – Divyang Desai Sep 08 '16 at 09:03
  • a textbox. I tried this after input control: string str = ViewBag.Res.ToString(); @Html.TextBox("Result",str) but it said: Cannot perform runtime binding on a null reference –  Sep 08 '16 at 09:04
  • Please note my sum method is of type void. –  Sep 08 '16 at 09:11
  • As per *How can I send result back to view?* your method should be look like my answer then and then you can return viewpage – Divyang Desai Sep 08 '16 at 09:16
  • But I don't want to have a new view. I want to show the result in the same view that I have already. –  Sep 08 '16 at 09:17
  • Even you can return specific view from your method like `return View("MyViewpage");` – Divyang Desai Sep 08 '16 at 09:20
  • I don't want to have a new view for result, just I want to show the result in the same view which I sent the data. –  Sep 08 '16 at 09:22
  • @user5032790 Read my comment carefully, you can pass your specific view. – Divyang Desai Sep 08 '16 at 09:23
  • @user5032790, Give your view name here:`MyViewpage` – Divyang Desai Sep 08 '16 at 09:25
  • Thanks. Now it did what I wanted. But isn't it regenerate my view again? is it a good way if I overload and regenerate my view again for just showing the result textbox? –  Sep 08 '16 at 09:28
  • *it a good way if I overload and regenerate my view again for just showing the result textbox?* of course not. In that case you can use an ajax to get your result. – Divyang Desai Sep 08 '16 at 09:31
  • Although I get the result now but my inputs are missing in the postback. Should I use session here or is a simpler way to keep input textboxes while postback? –  Sep 08 '16 at 09:34
  • @user5032790, *is a simpler way to keep input textboxes while postback?* yes you can use `ViewBag` for the same. – Divyang Desai Sep 08 '16 at 09:36
0

Using Jquery Ajax:
your view:

 

<body>

  <p>
   Number1:
   @Html.TextBox("num1")
  </p>
  <P>
   Number2:
   @Html.TextBox("num2")
  </P>
  <input type="submit" value="Calculate" id="submit"/>   
 
  <div id="result"></div>
 <!-- JS includes -->
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
 
 <script type="text/javascript">

     $(function () {
         $("#submit").click(function () {
             $.ajax({
                 method: "POST",
                 dataType: "json",
                 url: '@Url.Action("Index","Test")',
                 data: { 'num1': $("#num1").val(), 'num2': $("#num2").val() },
                 success: function (result) {
                     console.log(result);
                     $("#result").text(result);
                 }
             });
         })
     })

 </script>
</body>

your controller:

public class TestController : Controller
{
           [HttpGet]
            public ActionResult Index()
            {
                return View();
            }


            [HttpPost]
            public JsonResult Index(string num1, string num2)
            {
                var num11 = Convert.ToInt32(num1);
                var num21 = Convert.ToInt32(num2);
                int result = num11 + num21;

                return Json(result);
            }
}
Chinh Phan
  • 1,459
  • 19
  • 22