cannot get parameters from ajax call to controller razor - json

Simple usecase - get PartialView dynamically from AJAX call to update div in my main page after input select (dropdownlist) changed value.
Steps I took:
Created view (only, wihtout PageModel) with model declared with #model ViewModelCreateOperation.
Created checkbox on main page:
<select class="form-control" asp-items="#(new SelectList(Model.allExistingOperations))" onchange="PopulateForm(this.value); return false;"></select>
created scripts on main page:
<script>
function PopulateForm(value) {
var dataToPost = "{ operationName:" + value + "}";;
$.ajax({
type: "post",
url: '#Url.Content("/MeaningOfLifeRoutedName")',
data: dataToPost ,
contentType : 'application/json; charset=UTF-8',
success: function (data) {
$('#lubieplacki').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.status == 404) {
alert(thrownError);
}
}
});
}
</script>
created Controller in Controllers folder to return PartialView (becouse I cannot use "return PartialView("someview", someModel)" with PageModel already used as a inherit class.
namespace MyMysteriousApplication.Controllers
{
[Route("MeaningOfLifeRoutedName")]
public class MeaningOfLifeChangesController : Controller
{
private readonly MyMysteriousApplication.Models.TTSCDBContext _context;
public MeaningOfLifeChangesController(MyMysteriousApplication.Models.TTSCDBContext context)
{
_context = context;
}
public ViewModelCreateOperation viewModelCreateOperation { get; set; }
public IActionResult Index()
{
return RedirectToPage("../Index");
}
[HttpPost]
public ActionResult getMeaningOfLife(string operationName)
{
viewModelCreateOperation = new ViewModelCreateOperation();
viewModelCreateOperation = new ViewModelCreateOperation();
viewModelCreateOperation._entitiesSelectListItem = _context.Entities
.Select(a => new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem()
{
Value = a.Id.ToString(),
Text = a.EntityName
}).OrderByDescending(u => u.Text)
.ToList();
viewModelCreateOperation.MeaningOfLifeChanges = _context.MeaningOfLifeChanges.Where(u => u.OperationName.Contains(operationName)).OrderBy(u => u.ChangeId).FirstOrDefault();
return PartialView("../projectManagement/partialViewCreateNewMOL", viewModelCreateOperation);
}
}
}
Primary question:
I got null in parameters - I don't get why:
Bonus question:
I couldn't invoke my controller in any way (tried "/MeaningOfLifeChangeController/getMeaningOfLife" or "/MeaningOfLifeChange/getMeaningOfLife", with "~/MeaningOfLifeChangeController/getMeaningOfLife" and others combinations), so I added [Route("MeaningOfLifeRoutedName")] and [HttpPost] before method. I don't get why...
in Startup I have added controllers to initialize (JSON is for other stuff(API)):
services.AddControllersWithViews().
AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
options.JsonSerializerOptions.PropertyNamingPolicy = null;
options.JsonSerializerOptions.MaxDepth = 150;
}).AddRazorRuntimeCompilation();

It's not my answer, but Jiadong Meng helped me in ASP .NET Forums. I'm posting His answer:
Since the data you want to send is just a string type data, you need to stringify it like below.
var dataToPost = JSON.stringify(value);
Then in your Action, you should also add [FromBody] attribute.
public ActionResult getMeaningOfLife([FromBody]string operationName)

Related

Clearing session value while using Json in MVC

I am having a modal popup to create event and i want to allow only login user to see that page, save event and fetch event all are using json, but when i am going back after logout, session value is still present and all actions are getting performed, until i donot refresh the page, i want that no action should happen and session value should be cleared when i logout
public ActionResult Index()
{
if(Session["UserID"]==null)
{
return RedirectToAction("Index2","Login");
}
else
{
TempData["usersession"] = Session["UserID"].ToString();
}
return View();
}
<label id="session">#TempData["usersession"]</label>
//Javascript and Json
$(document).ready(function () {
username = $('#session').text();
});
function SaveEvent(data) {
alert(username);
$.ajax({
type: "POST",
url: '/home/SaveEvent',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calendar
fetchEvent();
$('#myModalSave').modal('hide');
//alert(username);
}
},
error: function () {
alert('failed');
}
});
While i am trying to alert username when i click on save it still showing the session value
have you tried this?
Session.Abandon(); // The Abandon method destroys all the objects stored in a Session object and releases their resources.
Session.Remove("YourItem"); //just removes current values
Session.Clear();// just removes all values
https://stackoverflow.com/a/5330288/7262120
public class VerifyUserAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var user = filterContext.HttpContext.Session["UserID"];
if (user == null)
filterContext.Result = new RedirectResult(string.Format("/User/Login?targetUrl={0}",filterContext.HttpContext.Request.Url.AbsolutePath));
}
}
[VerifyUserAttribute]
public ActionResult Index()
{
if(Session["UserID"]==null)
{
return RedirectToAction("Index2","Login");
}
else
{
TempData["usersession"] = Session["UserID"].ToString();
}
return View();
}

MVC5 Retrieve data with ajax, return json object instead of view

I have a simple function that searches for item I want in my database and retrieves it in my controller.
[HttpPost]
public ActionResult Index(string searchString)
{
var user = from m in db.Users select m;
if (!String.IsNullOrEmpty(searchString))
{
user = user.Where(s => s.UserName.Contains(searchString));
}
return View(user);
}
And then in my Javascript I send a value to search:
$('#test').click(function(e) {
e.preventDefault();
var user = "John";
$.ajax({
url: "#Url.Action("Index", "Users")",
data { "searchString": user },
type: "post",
success: function (saveResult) {
console.log(saveResult);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr, ajaxOptions, thrownError);
}
})
})
However of course all this does it return my view inside the console window which is something like:
But I would like to return a json object I can use.
just use the Json Action method.
return Json(user);
Edit:
As a side note, I would also set my return Type to be JsonResult for clarity
You just return as JsonResult such as below:
public ActionResult SomeActionMethod() {
return Json(new {foo="bar", baz="Blech"});
}

The result of json is empty when calling from cordova + angular.js

I am new to angular.js
I am trying to get json data as described in samples, as
(function () {
'use strict';
var module = angular.module('app', ['onsen']);
module.controller('GroupController', function ($scope, $http) {
$http.get("http://localhost/dinner/hOME/Categories")
.success(function (response) { $scope.categories = response; })
.error(function (data, status, headers, config) { alert(status); });
});
});
but code will go through error method with status=0, data =null
while when I open the link http://localhost/dinner/hOME/Categories in my browser there is response.
What is my mistake?
ServerSide Code (ASP.net MVC 3)
[HttpGet]
public JsonResult Categories()
{
IRecipeCategoryService rcSrv = ServiceFactory.Create<IRecipeCategoryService>();
var categoryList = rcSrv.FetchAll().Select(i => new {i.ID , i.Title }).OrderBy(j => j.Title).ToList();
return Json( categoryList
, JsonRequestBehavior.AllowGet);
}
Update (based on Sujata Chanda comments )
I have add these codes for CORS problem but it didn't help
module.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
Solution
from Christopher Marshall hint I made changes on server side based on this link
Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method
On server application adding this ActionFilter
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
base.OnActionExecuting(filterContext);
}
}
then tagging my action as below
[AllowCrossSiteJson]
[HttpGet]
public JsonResult Categories()
{
IRecipeCategoryService rcSrv = ServiceFactory.Create<IRecipeCategoryService>();
var categoryList = rcSrv.FetchAll().Select(i => new {i.ID , i.Title }).OrderBy(j => j.Title).ToList();
return Json( categoryList
, JsonRequestBehavior.AllowGet);
}

zend_rest + mysql + backbone

I implemented a RESTful application with Zend_Rest that saves info in a mysql db.
I'm going to handle the view with Backbone.js.
I'm looking for just a simple CRUD example. How to do that?
I didn't found any examples with Zend_Rest+Backbone, and the idea is to create it here, together.
UPDATE 0.1
How can I send (from backbone) and read (in the get/put/delete controller) the parameters?
CONTROLLER (modules>api>controllers>BackboneController.php)
class Api_BackboneController extends Zend_Rest_Controller
{
public function init(){
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
}
public function headAction(){
$this->getResponse()->setBody(null);
}
public function optionsAction(){
$this->getResponse()->setBody(null);
$this->getResponse()->setHeader('Allow', 'OPTIONS, HEAD, INDEX, GET, POST, PUT, DELETE');
}
// called from backbone with "read"
public function indexAction(){
// get the params
$resp = json_decode(file_get_contents('php://input'));
// send the same response
$this->getResponse()->appendBody(json_encode($resp));
}
// I can't reach this one from backbone, WHY?
public function getAction(){}
// called from backbone with "update"
public function putAction(){}
// called from backbone with "delete"
public function deleteAction(){}
}
VIEW (modules>default>views>scripts>index.phtml)
var MyModel = Backbone.Model.extend({
defaults: {
text: "default text"
},
url: "/base/api/backbone",
options: {
success: function(data){
console.log(data);
},
error: function(x, t, e){
console.log("error: " + t + ", " + e);
}
}
});
var myModel = new MyModel();
Backbone.sync("read", myModel, myModel.options);
})(jQuery);

How to pass a JSON object to an action

I have the following jQuery code in a View in MVC3. I want to load a partial view (named OffshoreECore) in a div (#Form) depending on the JSON object passed in the success function. Here's the code:
var inputParamtrs = { 'HeadId': $('#ExpenseId').val(), MProjid': $('#MProjid').val() };
$.ajax({
type: "POST",
url: "/Expenses/Edit",
data: inputParamtrs,
success: function (json) {
('#Form').load('#Url.Action("OffShoreECore", *What comes here ?!?*)');
}
Thanks.
The second parameter of load() is the data which should be sent to the specified URL along with the request. To send your JSON string, try this:
success: function (json) {
$('#Form').load('#Url.Action("OffShoreECore")', json);
}
You example code is also missing a ' delimiter from the second key in inputParamtrs and the $ from the selector in success, but I guess they're just typos.
$.getJSON("/Expenses/Edit",
{
HeadId: $('#ExpenseId').val(),
MProjid: $('#MProjid').val()
},
function (data) {
elementForResult.innerHTML = data;
});
In Controller:
public JsonResult Edit(int HeadId, int MProjid)
{
...
var result = SerializeControl("~/Views/Expenses/Edit.cshtml", null);
return Json(result, JsonRequestBehavior.AllowGet);
}
private string SerializeControl(string controlPath, object model)
{
var control = new RazorView(ControllerContext, controlPath, null, false, null);
ViewData.Model = model;
var writer = new HtmlTextWriter(new StringWriter());
control.Render(new ViewContext(ControllerContext, control, ViewData, TempData, writer), writer);
string value = writer.InnerWriter.ToString();
return value;
}