Pixelord
Pixelord

Reputation: 641

ASP.Net MVC: posting/binding/saving hidden field to model

I am new in ASP.Net MVC. I have a model that has following fields: Event Name, Start time, End time, owner.

Now in the view I have similar to this (to render and post updated data through form):

<tbody>
    @if (Model.Events != null)
    {
       for (int i = 0; i < Model.Events.Count; i++)
       {
        <tr class="event-record">
        <td>@Html.TextBoxFor(m => m.Events[i].EventName, new { @class = "form-control" })</td>
        <td>@Html.TextBoxFor(m => m.Events[i].StartTime, new { @class = "form-control" })</td>
        <td>@Html.TextBoxFor(m => m.Events[i].EndTime, new { @class = "form-control" })</td>
        </tr>
        }
    }
</tbody>

Now my view doesn't have any input text field for owner and I intent to fill that owner field by javascript and post that information along with other fields that are visible.

[UPDATE]Here is my HTTP Post action:

[HttpPost]
[MultipleButton(Name = "action", Argument = "EventSaveExit")]
public ActionResult EventSaveExit(MasterEvent masterEvents)
{
    CreateUpdateEvent(masterEvents);
    return Redirect("/");
}

How can I achieve that result?

Thanks in advance!

Upvotes: 0

Views: 6981

Answers (2)

Shyju
Shyju

Reputation: 218722

You should add a hidden field for Owner property. You can use the HiddenFor helper method to create the hidden field.

<tr class="event-record">
    <td>
        @Html.TextBoxFor(m => m.Events[i].EventName, new {@class = "form-control"})
        @Html.HiddenFor(m => m.Events[i].Owner, new {@class = "form-control ownerItem"})
    </td>
</tr>

You can use javascript to set the value of your hidden field. The below code use jQuery and will set all owner hidden field's value to "Scott" on the document ready event.

$(function(){
    //set to all input element's with ownerItem css class
    $("input.ownerItem").val("Scott");
});

Never trust client side data

If you are trying to save the current username as the Owner property value for each record, you should not do that in client side because anyone can open your site and using browser dev tools, update the value of the hidden field to any name and save the record. You should be doing that in server side.

[HttpPost]
public ActionResult EventSaveExit(MasterEvent masterEvents)
{
   foreach (var eventVm in masterEvents.Events)
   {
      eventVm.Owner = "Set the value here";
   }
   // now continue saving
   CreateUpdateEvent(masterEvents);
   return Redirect("/");
}

Upvotes: 1

NikolaiDante
NikolaiDante

Reputation: 18639

Try

@Html.HiddenFor(m => m.Events[i].Owner)

That should give you a hidden text box, bound to the Owner property.

It basically renders to an <input type="hidden" ... element

Upvotes: 2

Related Questions