SWA SWA - 1 month ago 21
ASP.NET (C#) Question

Correctly display data in View and save it using HiddenFor and DisplayFor

Not sure how to better express the question. I want to use hiddenFor field to save record_time to database while displaying date in a html.display or similar to that field without editing.

CREATE action

public ActionResult Create()
{
Record newRecord = new Record();
newRecord.user_id = 1; //let it be 1 for simplicity
newRecord.record_time = System.DateTime.Now;
return View(newRecord);
}


CREATE view

<div class="form-group">
@Html.LabelFor(model => model.user_id, "User name", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.HiddenFor(model => model.user_id)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.record_time, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.HiddenFor(model => model.record_time)

//this line I'm concerned about
@Html.DisplayFor(model => model.record_time, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>


QUESTIONS

1) About user_id. Is it correct to use hiddenFor for new record, not editorFor?

2) About record_time. Is it correct to use both hiddenFor and displayFor? which one will be used to send data back to database? What is the correct way to just display a predefined datetime info and send it then to the database?

Answer

A form only submits the name/value pairs of its form controls (input, select, textarea) and DisplayFor() does not generate a form control.

If you want to format the date using DisplayFor(), then you can use the DisplayFormatAttribute, for example

[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime record_time { get; set; }

or you can just use <div>@Model.record_time.ToString("MM/dd/yyyy")</div>

Note that DisplayFor() renders just text, not an element, and it does not have an overload that accepts htmlAttributes (there is no element to apply attributes to, so its just

@Html.DisplayFor(m => m.record_time)

As a side note, the names of both you properties indicate they are for the user who created/edited the record and the date the record was created. If that is the case, you view should not include any inputs for those values. Both should be set in the POST method immediately before you save the data model. And if its a create view, displaying the record_time (assuming it is the date the record was created) makes no sense either (it has not been created yet).

Comments