Reputation: 385
I only need to update one field in the database, the name from a form. I use hidden fields to update/keep the value of the rest. This i my view
@using (Ajax.BeginForm("ChangeHeaderName", "Rooms",
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "Post",
OnSuccess = "OnSuccess",
OnFailure = "OnFailure"
}))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.RoomId)
@Html.HiddenFor(model => model.RoomLink)
@Html.HiddenFor(model => model.Alias)
<div class="room-header-container">
<h2>@Html.EditorFor(m => m.Name, new { htmlAttributes = new { @id = "room-header", @class = "edit-header" } })</h2>
</div>
}
Feels stupid to use @Html.HiddenFor
for every field I don't want to update.
This is my controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ChangeHeaderName(Room room)
{
if (ModelState.IsValid)
{
db.Entry(room).State = EntityState.Modified;
db.SaveChanges();
return PartialView("_UpdateHeader", room);
}
return View(room);
}
Is there a better solution without hidden fileds?
Edit/Update
I have this in my model
public int RoomId { get; set; }
public string Name { get; set; }
public Guid RoomLink { get; set; }
public bool UseAlias { get; set; }
public string Alias { get; set; }
public DateTime Created { get; set; }
And I want to display all of this to the user, but the user should only be able to edit Name
If I create a ViewModel
with only Name
public string Name { get; set; }
Can't I display the rest. I want to display all but only update Name
Upvotes: 1
Views: 274
Reputation: 385
Found solution here: https://stackoverflow.com/a/23380525/5369591
if (ModelState.IsValid)
{
db.Registrations.Attach(registration); // attach in the Unchanged state
db.Entry(registration).Property(r => r.Date).IsModified = true;
// Date field is set to Modified (entity is now Modified as well)
db.SaveChanges();
return RedirectToAction("Index");
}
Upvotes: 1
Reputation: 496
Yes, you can put disabled attribute for all field which you want to Ignore.
With Jquery you can do this way
$(document).ready(function(){
$('input[type="hidden"]').attr("disabled","disabled");
})
Upvotes: 0