Reputation: 14610
I want to change the value of an enumdropdownlist from active to inactive in my database by doing some ajax call WITHOUT refreshing my page? How do I do this? javascript method or ajax.beginform? not sure here...
I tried ajax.beginform and the call gets made the to the controller ok, but then it tries to refresh/render a view by returning it as a actionresult. I don't want it to refresh the view because I loose my viewmodel data. I thought ajax.beginform only refreshed what was inside the form? Do I need to perform this in a javascript method instead? What do I do to prevent a view from being refreshed/rendered in my action method?
here is my ajax form. If I return a view I loose all the 'Model' view data, so model.statusenabled is null! I don't understand why its null because it's outside of the ajaxform...
@if (Model.StatusEnabled)
{
using (Ajax.BeginForm("UpdateStatus", "Student", new AjaxOptions
{
HttpMethod = "post",
OnSuccess = "dotcolor();"
}))
{
@Html.EnumDropDownListFor(model => model.Status, new { @class = "btn btn-default btn-lg dropdown-toggle", onchange = "this.form.submit();", id = "enumstatus" })
}
}
else
{
@Html.EnumDropDownListFor(model => model.Status, new { @class = "btn btn-default btn-lg dropdown-toggle", disabled = "disabled" })
}
here is my action method
[HttpPost]
public ActionResult UpdateStatus()
{
//update database
// don't return view because it gets refreshed
// and I have to re pass in my viewmodel
return View("Edit");
}
if I change the return type to void in UpdateStatus() it still attemptsto return a view called UpdateStatus. Not what I want.
Upvotes: 1
Views: 5262
Reputation:
This is relatively easy using jquery and ajax to post the selected value
Html
@Html.EnumDropDownListFor(m => m.Status, new { @class = "btn btn-default btn-lg dropdown-toggle" })
Script
var id = '@Model.ID'; // store the ID of the student (change to suit your property name)
var url = '@Url.Action("UpdateStatus", "Student")';
$('#Status').change(function() {
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function(data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
}
}
Controller
[HttpPost]
public ActionResult UpdateStatus(int ID, EmployeeStatus Status) // assumes the enum is typeof EmployeeStatus
{
// update the employees status based on the parameters
return Json(true); // or return Json("some message")
}
Note, you will probably want to check that the status was indeed updated, for example in a catch block you might return Json(null)
or return Json("some error message")
which you could then use to display a message on the page
Upvotes: 3