3

I am new to MVC 4, What I want to do is, make a label that display increment integer

in cshtml page

@Html.LabelFor(m => m.Increment, Model.Increment)

in controller page

public ActionResult Index(IncrementModel IM){
    IM.Increment ++;
    return View(IM);
}

The starting result is 0, press one this it increase to 1, then the value forever is 1 no matter how many time I press.

Rahul Nikate
  • 6,192
  • 5
  • 42
  • 54
Yu Yenkan
  • 745
  • 1
  • 9
  • 32

2 Answers2

1

LabelFor helper method render a label like this.

<label for="Increment">Increment</label>

This won't event show the value of your Increment property of the mdoel. If you want that, you may simply render it like

<p>@Model.Increment</p>

Or using the DisplayFor() helper method.

@Html.DisplayFor(s=>s.Increment)

This will also simply render the value to your page. When you post the form, It is not going to post the current value in the page to the HttpPost action. For that you need a form field. It can be a textbox, hidden field etc..

@using(Html.BeginForm())
{
   @Html.DisplayFor(s=>s.Increment)
   @Html.HiddenFor(s => s.Increment)
   <input type="submit"/>
}

But now also when you post the value and increment it in the action method and send it back, The input fields(hidden field) value won't be updated every time with the new value. Because the ModelStateDictionary has some value for this property now, which is the value after the first update.This value will be used when we render the hidden field for Increment property. That is the reason you are seeing 1 as the value and it never changes.

What you should do is explicitly remove this item from the ModelStateDictionary.

[HttpPost]
public ActionResult Index(IncrementModel IM)
{
    IM.Increment++;
    ModelState.Remove("Increment");
    return View(IM);
}
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • can't, the value did not save in ModalState – Yu Yenkan Dec 31 '15 at 04:53
  • 1
    I just verified it in a simple MVC sample project and it totally worked. I am sure you are missing something from what i posted. Please double check. – Shyju Dec 31 '15 at 05:05
0

A label is only for display. It's value isn't submitted back to server. Use a textbox instead and place it in a form.

@Html.TextBoxFor(m => m.Increment);
Akshey Bhat
  • 8,227
  • 1
  • 20
  • 20
  • If I may suggest adding a hidden variable that will be submitted instead of textbox, that's how I would do it – sameh.q Dec 31 '15 at 04:33