According to MSDN an ActionResult is used to return more than one type of result depending on the method.
You decide which type of action result to return based on the task that the action method is performing.
I just started a new job where their MVC site is so complex and intricate that certain changes are really dificult to make without breaking what is already working.
My question is : Using Ajax.BeginForm, is it possible to return either JSON or a partial view from the same action method depending on a parameter value?
Here is a simple example
@using (Ajax.BeginForm("AddNetworkLocationContact", "NetworkLocations", new AjaxOptions() {UpdateTargetId = "networkLocationList", OnSuccess = "onContactAddSuccess"}))
It hits the controller which (at this point) has access to a viewmodel property called PartialBeingCalledFrom
.
Depening on where it's called from (either Guide, or EmergencyContactsTable) I want it to render either a JSON response or a partial view response. This line does not work.
if(viewModel.PartialBeingCalledFrom == CallerLocation.Guide)
return PartialView("_NetworkLocationList", GetNetworkLocationsViewModel(viewModel.ClientId, "New Emergency Contact has been added"));
This line does
return Json(new
{
status = true,
updatedData = new
{
name = returnName,
number = returnListOfNumbers,
availability = viewModel.ExistingContactAvailablity,
contactId = viewModel.ExistingContactId,
docId = (string)network._id,
updatedContactsArray = (object)JsonConvert.SerializeObject(contactServices.GetContactPhoneNumberDictionary(ClientId.Value), Formatting.None)
}
The issue I am assuming is with the fact that I declare an OnSuccess
method in my Ajax.BeginForm
which gets run correctly when I return JSON data. I am assuming that jquery is not able to tell if what is being receieved is JSON or is a view and hence doesn't know when to execute the partial view upone the UpdateTargetId
provided in the above ajax call. Is there a good way to achieve this type of functionality?
Dupe that didn't show up in any searches until I posted this!
ASP.NET MVC controller actions that return JSON or partial html