Show content in textboxfor

0

I would like to know how to display the value of a property within a textboxfor . I have the following code:

@model Calcular.Models.Conta

@{
ViewBag.Title = "Somar";
}

<h2>Somar</h2>

@using (Html.BeginForm("Action", "Conta")) { 
<table>
<tr>
    <td>@Html.TextBoxFor(m => m.Num1)</td>
</tr>
<tr>
    <td>@Html.TextBoxFor(m => m.Num2)</td>
</tr>
<tr>
    <td><input type="submit" name="Somar" value="Somar"/></td>
    <td><input type="submit" name="Subtrair" value="Subtrair"/></td>
</tr>

<tr>
    <td>@Html.TextBoxFor(m => m.Result)</td> 
</tr>
</table>
}

Controller:

[HttpPost]
   [HttpParamAction]
    public ActionResult Somar(Conta conta)
    {

        conta.Somar(conta.Num1, conta.Num2);
        return View("Somar", conta);
    }

    [HttpParamAction]
    [HttpPost]
   public ActionResult Subtrair(Conta conta)
    {
        conta.Sub(conta.Num1, conta.Num2);
        return View("Somar", conta);
    }
    
asked by anonymous 23.03.2015 / 20:06

1 answer

0

I get the impression that I already answered this in another question, but come on.

Since the sum (or subtraction) field is not benchmarked, it is best to make a class that is very similar to the class that represents your Model , but with a few more fields, only not mapped to a bank.

So we would have a class like this:

public class ContaViewModel
{
    public int Num1 { get; set; }
    public int Num2 { get; set; }
    [NotMapped]
    public int Resultado { get; set; }

    public void Somar() 
    {
        Resultado = Num1 + Num2;
    }

    public void Sub() 
    {
        Resultado = Num1 - Num2;
    }
}

This attribute [HttpParamAction] you possibly got him out . It is not standard in ASP.NET MVC. It is used to direct POST to a given Action of its Controller .

As I removed the parameters of Somar and Sub (because they are not necessary since the properties already exist within the class), your Controller would look like this:

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

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

For TextBoxFor , just do the following:

@model Calcular.Models.Conta

@{
    ViewBag.Title = "Somar";
}

<h2>Somar</h2>

@using (Html.BeginForm("Action", "Conta")) { 

    <table>

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

        <tr>
            <td>@Html.TextBoxFor(m => m.Resultado)</td> 
        </tr>

    </table>

}
    
24.03.2015 / 05:17