Pass values from one form to one method in Model and return the result to another textbox on the Form

2

I have a very simple form with 3 textbox and a button. I would like to get the value of the first two textbox by clicking the button and move to a method present in my model and after that return that result to the third textbox . I'm having difficulty passing the values and returning using the controller. I am a beginner in Asp.net mvc, if anyone can help. Thank you.

I have this Model method I want to use:

public class Conta
{
    [Required]
    public int Num1 { get; set; }
    [Required]
    public int Num2 { get; set; }
    public double Result { get; set; }

    public int Somar(int num1, int num2)
    {
        return num1 + num2;
    }

That's no controller:

 public ActionResult Index()
    {
        return View();
    }

    private static Conta _conta = new Conta();
    [HttpPost]
    public ActionResult Somar(Conta conta)
    {
        _conta.Somar(conta.Num1, conta.Num2);
        return View();
    }

And this in the index:

<tr>
    <td>@Html.TextBoxFor(ContaModel => ContaModel.Num1)</td>
</tr>
<tr>
    <td>@Html.TextBoxFor(ContaModel => ContaModel.Num2)</td>
</tr>
<tr>
    <td><input type ="submit" value="Somar" name="Somar"/></td>
</tr>

</table>

As a beginner, I do not know if this is the right way to do it.

    
asked by anonymous 20.03.2015 / 15:52

2 answers

1

Here is an alternative to the answer of Gypsy (which by the way is quite complete):

Here I will be using an AJAX request to perform the sum and return the value.

Model

using System;
using System.ComponentModel.DataAnnotations;

namespace MvcApp
{
    public class Conta
    {
        [Required]
        public int Num1 { get; set; }
        [Required]
        public int Num2 { get; set; }
        public int Result { get; set; }

        public int Somar()
        {
            this.Result = this.Num1 + this.Num2;
            return this.Result;
        }
    }
}

Controller

using System;
using System.Web.Mvc;
using System.Collections.Generic;

namespace MvcApp
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View(new Conta());
        }


        [HttpPost]
        public JsonResult Soma(Conta conta)
        {   
            conta.Somar();
            return Json(conta);
        }
    }
}

View

@model MvcApp.Conta
@{
    Layout = null;
}

<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->

<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script type="text/javascript">
            var virtualPath = "@Url.Content("~/")";
        </script>
    </head>

    <body>
        <div class="container">
            <div>
                @Html.LabelFor(Model => Model.Num1)
                @Html.TextBoxFor(Model => Model.Num1)
            </div>
            <div>
                @Html.LabelFor(Model => Model.Num2)
                @Html.TextBoxFor(Model => Model.Num2)
            </div>
            <div>
                @Html.LabelFor(Model => Model.Result)
                @Html.TextBoxFor(Model => Model.Result, new { @readonly = "readonly", @disabled = "disabled" })
            </div>
            <div>
                <input type ="button" value="Somar" name="Somar"/>
            </div>
        </div>
        <script type="text/javascript">
            var form = {};
            window.onload = function() {
                form.Num1 = document.querySelector("[name='Num1']");
                form.Num2 = document.querySelector("[name='Num2']");
                form.Result = document.querySelector("[name='Result']");
                form.Somar = document.querySelector("[name='Somar']");

                form.Somar.onclick = function (event) {
                    event.stopPropagation();
                    event.preventDefault();
                    somar();
                };
            }

            var urlParameters = function(json) {
                var params = "";
                for (var key in json) {
                    var value = json[key];
                    params += "&" + encodeURIComponent(key) + '=' + encodeURIComponent(value);
                }
                return params.substring(1);
            }

            var somar = function () {
                var conta = {
                    Num1: form.Num1.value,
                    Num2: form.Num2.value,
                    Result: form.Result.value
                };
                var params = urlParameters(conta);

                var xmlHttp = new XMLHttpRequest();
                xmlHttp.open("POST", virtualPath + "Home/Soma", true);
                xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

                xmlHttp.onreadystatechange = function() {
                    if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                        var conta = JSON.parse(xmlHttp.responseText);
                        form.Result.value = conta.Result;
                    }
                }
                xmlHttp.send(params);
            }

        </script>
    </body>
</html>

DotNetFiddle

    
20.03.2015 / 21:00
2

There are some pointless things in your example. Let's go to them:

private static Conta _conta = new Conta();

You do not need to initialize a Model outside an Action of a Controller . There is no use in this, and the role of a Model is to represent data.

Initially Models are anemic (only with properties) objects, but may contain some built-in rules, validations, and attributes.

This part is ok:

public ActionResult Index()
{
    return View();
}

Now this part, if the purpose is to show something on the screen, you must send the object that will be shown to the screen. As it is this does not happen:

[HttpPost]
public ActionResult Somar(Conta conta)
{
    _conta.Somar(conta.Num1, conta.Num2);
    return View();
}

In addition, you are instantiating a Model to perform two-parameter operations of another Model that implements the same class. It does not make any sense.

The correct one would look something like this:

conta.Somar(conta.Num1, conta.Num2);

It would be better not to need to pass any parameters, after all the properties are of the object itself:

public void Somar()
{
    this.Result = this.Num1 + this.Num2;
}

That is, the method would look like this:

conta.Somar();

Of course, for Result is just a calculated field, something else needs to be noted:

public class Conta
{
    [Required]
    public int Num1 { get; set; }
    [Required]
    public int Num2 { get; set; }
    [NotMapped]
    public double Result { get; set; }

    public void Somar()
    {
        this.Result = this.Num1 + this.Num2;
    }
}

[NotMapped] tells the context that the field should not be mapped to the database, ie that the property exists in the class but is not a column of a table or collection of a database.

Returning to the return, done the calculation, you need to send the object ready to View . This can be done like this:

[HttpPost]
public ActionResult Somar(Conta conta)
{
    conta.Somar();
    return View(conta);
}

In this case, we are calling a View named Somar.cstml . It needs to look something like this:

@model MeuProjeto.Models.Conta

<div>
    Num1: @Model.Num1
</div>
<div>
    Num2: @Model.Num2
</div>
<div>
    Soma: @Model.Result
</div>

If you want to send the result to another View , specify as the first argument the name of this View :

[HttpPost]
public ActionResult Somar(Conta conta)
{
    conta.Somar();
    return View("OutraView", conta);
}

In this case, the result will be printed using a View whose file is OutraView.cshtml .

    
20.03.2015 / 18:32