Lang thang
Lang thang

Reputation: 291

MVC4 - @html.HiddenFor and re-bind value when insert successfully

let say I have a View, bind to Student Model with 2 properties: ID, Name.

ID is primary key and is set as Identity column in SQL.

Here is the situation:

  1. Load Create page, ID and Name will be:

    @model Student
    
    @Html.HiddenFor(x => x.ID);
    @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })  
    
  2. Submit form via Jquery and call API, when insert successfully, it returns ID.

  3. when return $.ajax.done, I got the value of ID.

  4. How could I bind this value to HiddenFor(x => x.ID) without reload the page?

Please advise.

Thanks.

Upvotes: 0

Views: 313

Answers (1)

Mark
Mark

Reputation: 2063

@Html.HiddenFor(x => x.ID); will help you create a hidden input with id and name are the same with your field, while value is the same with your field's value. So, if ID has value 1, it will create <input id="ID" name="ID" type="hidden" value="1" />

Then, when you want to bind a new value to this input in your jQuery, you can just change its value

var ID = 2;
$('#ID').val(ID);

Selector # is used to select an element with a specific ID.

Upvotes: 1

Related Questions