mvc json request life cycle - asp.net-mvc

I'm pretty new to asp.net and MVC.
I was trying to use json request and populate some text boxes.
but I noticed when I'm using json, I can not access values of the other text boxes in my view.
for example
string s2 = Request.Form["selectedTestCategory"];
would generate s2 = null, when I debug.
but if I put a submit button on the page, the value is not null. (And so far I know I can only pass one parameter to my JSON method in controller)
My question is what happens when I start a json request? and why I can not get a value from Request.Form[...]
Thanks,
Update:
This is my json
<script>
$(document).ready(function() {
$('select#testStationUniqueId').change(function() {
var testStation = $(this).val();
$.ajaxSetup({ cache: false });
$.ajax({
url: "TestInput/getTestStationInformation/" + testStation,
type: 'post',
success: function(data) {
$('#driveDetailDiv').empty();
for (var i = 0; i < data.length; i++) {
$.post('TestInput/Details/', { id: data[i] }, function(data2) {
$('#driveDetailDiv').append(data2);
});
}
}
});
});
});
And this is in my controller
public PartialViewResult Details(string id)
{
//DriveDetails t = new DriveDetails(id);
//return PartialView("DriveDetailsPartial", t);
test_instance_input_model ti = new test_instance_input_model();
string s2 = Request.Form["selectedTestCategory"];
repository.setTestInstanceAttributes(ti, id);
return PartialView("TestInstancePartial", ti);
}
the s2 is null in Details, but if I use a submit button, it will have the correct value.
so I'm trying to figure out why it is null when I send a json request.

In your JavaScript your not including any data in the jQuery ajax request (see jQuery ajax). Therefore jQuery isn't adding any request parameters. You need to include a data object which jQuery will turn into parameters i.e. the more properties in the data object the more parameters in the request.
$.ajax({
url: '',
data: { selectedTestCategory: 'category' },
dataType: 'post',
success: function() {}
});
Also, in your controller you can shortcut to the request parameter.
string s2 = Request["selectedTestCategory"];

Related

How to get value of form filed card_number to pass to the controller?

How would I get the value of card_number to pass to the controller?
Every time I submit the form I get NULL in the form variable
View:
#Html.EditorFor(model => model.card_number, new { htmlAttributes = new { #id = "card_number" } })
<script>
var frm = $('#formFilter');
function OnFormSubmit() {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: function (frm) {
frm.card_number = $('#card_number').val();
},
success: function (data) {
$("#dataResult").html(data);
$('#dataTable').DataTable({
"dom": 'lifrtp'
});
}
});
}
</script>
controller:
private List<testtest> GetListChanges(Report changeControl)
{
...logic here....
return returnListhere;
}
The data property of the $.ajax method options should be an object or string which represents your data. With your current code you are setting a function to that.
var d = {
card_number: "1234",
someOtherPropertyNameOfReport: "Hello"
};
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: JSON.stringify(d),
contentType:"application/json",
success: function (data) {
console.log(data);
}
});
Now jquery will send the request with Content-Type request header value set to application/json and request data (the stringified version of your JavaScript object) in the request body and model binder will be able to properly read and map it to your view model, assuming the structure of the view model matches with your JavaScript object structure.
As suggested in the comment, try to use serialize() method. It is simply and you do not need to manually build the object.
Also your controller action method should be public

Open .aspx page with report controller in MVC

I have an MVC .cshtml page with a button. It's in a grid and I am passing the row ids to the controller using the jquery
<button type="submit" id="btn_View" name="view"
class="btn_View">
$(".btn_View_Question").click(function () {
var json = [];
var obj = {};
var rowID = $(this).closest('tr').attr('id');
obj.RowId= rowID ;
console.log(obj);
json.push(obj)
var responseDetails = JSON.stringify(json);
$.ajax({
url: "/Home/View",
type: "POST",
data: responseDetails,
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
});
});
In the controller class I am redirecting to a aspx report page as follows
public RedirectResult ViewQuestionnaire(string[] id)
{
var reportParameters = new Dictionary<string, string>();
reportParameters.Add("ID", id[0]);
Session["reportParameters"] = reportParameters;
return Redirect("../Reports/ViewQuestionarie.aspx");
}
The aspx page is not loading. When I debug it the page_load of the aspx page also executing. What might the wrong thing I am doing here
Redirect is going to return a 302 response with the new url as the location header value.You should not be making the call to an action method which returns a 302 response from an ajax call.
Looks like you want to set some data to Session. You may use your ajax call to still do that part. Instead of returning a 302 response,return a json data structure with the url you want the browser to be redirected.
public ActionResult ViewQuestionnaire(string[] id)
{
var reportParameters = new Dictionary<string, string>();
reportParameters.Add("ID", id[0]);
Session["reportParameters"] = reportParameters;
return Json(new {status = "success", url="../Reports/ViewQuestionarie.aspx"});
}
And in the success / done event of the ajax call, you can read the url property of the json response coming back and use that to do the redirection.
$.ajax({
//Omitted some parameters
success: function(res) {
if (res.status === "success") {
window.location.href = res.url;
}
}
});

Ajax Request issue with ASP.NET MVC 4 Area

Today i discovered something weird, i have regular asp.net mvc 4 project with no such ajax (just post, get). so today i need ajax request, i did an ajax action with jquery in controller and it didn't work out. Here is my code
Areas/Admin/Controllers/BannersController
public JsonResult SaveOrder(string model)
{
bool result = false;
if (!string.IsNullOrEmpty(model))
{
var list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<int>>(model);
result = repository.SaveOrder(list);
}
return Json(result, JsonRequestBehavior.AllowGet);
}
View side (Its in area too)
$(document).ready(function () {
$("#saveOrder").click(function () {
var data = JSON.stringify($("#list_banners").nestable('serialize'));
$.ajax({
url: '#Url.Action("SaveOrder", "Banners", new { area = "Admin" })',
data: { model: data },
success: function (result) {
if (result) {
toastr.success('Kaydedildi.');
}
else {
toastr.error('kaydedilemedi.');
}
},
error: function (e) {
console.log(e);
}
});
});
});
i've already tried everything i know, which is $.post, $.get, ajax options, trying request from out of area etc.. just request can't reach action
and here is the errors ,
http://prntscr.com/297nye
error object
http://prntscr.com/297o3x
Try by specifying the data format (json) you wand to post to server like and Also change the way you pass data object in JSON like this :
var data = $("#list_banners").nestable('serialize');
$.ajax({
url: '#Url.Action("SaveOrder", "Banners", new { area = "Admin" })',
data: JSON.stringify({ model: data }),
dataType: 'json',
contentType: "application/json",
...
I had same issue, but after spending too much time, got solution for that. If your request is going to your specified controller, then check your response. There must be some problem in your response. In my case, response was not properly converted to JSON, then i tried with passing some values of response object from controller using select function, and got what i needed.

How to ajax/post JSON array to ASP MVC

Trying to do a post including some JSON data that has an array of integers in it. Pressing the button on my page to perform the post is getting to the action, but the expected data is not there (the two int[] variables are null). Doing a network profile while posting shows that the request body includes data like this:
groups%5B%5D=2&groups%5B%5D=3&alerts%5B%5D=5&alerts%5B%5D=9
Javascript:
$('#modal-save').click(function() {
var selectedGroups = [];
var selectedAlerts = [];
$('input:checked').filter('[data-group="true"]').each(function() {selectedGroups.push($(this).data('id')); });
$('input:checked').filter('[data-group="false"]').each(function() {selectedAlerts.push($(this).data('id')); });
$.ajax({
type:'Post',
dataType: 'json',
url:'#Url.Action("UpdateAlertStores", new { alias = ViewBag.Alias})',
data: {groups: selectedGroups, alerts: selectedAlerts},
});
MVC Action:
[HttpPost]
public bool UpdateAlertStores(string alias, Guid? groupID, Guid? storeID, int[] groups, int[] alerts)
{
return true;
}
add traditional:true
traditional: true,
type:'Post',
dataType: 'json',
url:'#Url.Action("UpdateAlertStores", new { alias = ViewBag.Alias})',
data: {groups: selectedGroups, alerts: selectedAlerts},
after this changing your url looks like:
groups=2&groups=3&alerts=5&alerts=9

How to send a model in jQuery $.ajax() post request to MVC controller method

In doing an auto-refresh using the following code, I assumed that when I do a post, the model will automatically sent to the controller:
$.ajax({
url: '<%=Url.Action("ModelPage")%>',
type: "POST",
//data: ??????
success: function(result) {
$("div#updatePane").html(result);
},
complete: function() {
$('form').onsubmit({ preventDefault: function() { } });
}
});
Every time there is a post, I need to increment the value attribute in the model:
public ActionResult Modelpage(MyModel model)
{
model.value = model.value + 1;
return PartialView("ModelPartialView", this.ViewData);
}
But the model is not passed to the controller when the page is posted with jQuery AJAX request. How can I send the model in the AJAX request?
The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.
As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.
For example, the Javascript:
var values =
{
"Name": "Chris",
"Color": "Green"
}
$.post("#Url.Action("Update")",values,function(data)
{
// do stuff;
});
The model:
public class UserModel
{
public string Name { get;set; }
public string Color { get;set; }
public IEnumerable<string> Contacts { get;set; }
}
The controller:
public ActionResult Update(UserModel model)
{
// do something with the model
return Json(new { success = true });
}
If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.
In our app, we do this with an extension method:
public static class JsonExtensions
{
public static string ToJson(this Object obj)
{
return new JavaScriptSerializer().Serialize(obj);
}
}
On the view, we use it to render the model:
<script type="javascript">
var model = <%= Model.ToJson() %>
</script>
You can then pass the model variable into your $.ajax call.
I have an MVC page that submits JSON of selected values from a group of radio buttons.
I use:
var dataArray = $.makeArray($("input[type=radio]").serializeArray());
To make an array of their names and values. Then I convert it to JSON with:
var json = $.toJSON(dataArray)
and then post it with jQuery's ajax() to the MVC controller
$.ajax({
url: "/Rounding.aspx/Round/" + $("#OfferId").val(),
type: 'POST',
dataType: 'html',
data: json,
contentType: 'application/json; charset=utf-8',
beforeSend: doSubmitBeforeSend,
complete: doSubmitComplete,
success: doSubmitSuccess});
Which sends the data across as native JSON data.
You can then capture the response stream and de-serialize it into the native C#/VB.net object and manipulate it in your controller.
To automate this process in a lovely, low maintenance way, I advise reading this entry that spells out most of native, automatic JSON de-serialization quite well.
Match your JSON object to match your model and the linked process below should automatically deserialize the data into your controller. It's works wonderfully for me.
Article on MVC JSON deserialization
This can be done by building a javascript object to match your mvc model. The names of the javascript properties have to match exactly to the mvc model or else the autobind won't happen on the post. Once you have your model on the server side you can then manipulate it and store the data to the database.
I am achieving this either by a double click event on a grid row or click event on a button of some sort.
#model TestProject.Models.TestModel
<script>
function testButton_Click(){
var javaModel ={
ModelId: '#Model.TestId',
CreatedDate: '#Model.CreatedDate.ToShortDateString()',
TestDescription: '#Model.TestDescription',
//Here I am using a Kendo editor and I want to bind the text value to my javascript
//object. This may be different for you depending on what controls you use.
TestStatus: ($('#StatusTextBox'))[0].value,
TestType: '#Model.TestType'
}
//Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox
//selected value. This puzzled me due to the conversion to Json object in the Ajax call.
//By parsing the Type to an int this worked.
javaModel.TestType = parseInt(javaModel.TestType);
$.ajax({
//This is where you want to post to.
url:'#Url.Action("TestModelUpdate","TestController")',
async:true,
type:"POST",
contentType: 'application/json',
dataType:"json",
data: JSON.stringify(javaModel)
});
}
</script>
//This is your controller action on the server, and it will autobind your values
//to the newTestModel on post.
[HttpPost]
public ActionResult TestModelUpdate(TestModel newTestModel)
{
TestModel.UpdateTestModel(newTestModel);
return //do some return action;
}
I think you need to explicitly pass the data attribute. One way to do this is to use the
data = $('#your-form-id').serialize();
This post may be helpful.
Post with jquery and ajax
Have a look at the doc here..
Ajax serialize
you can create a variable and send to ajax.
var m = { "Value": #Model.Value }
$.ajax({
url: '<%=Url.Action("ModelPage")%>',
type: "POST",
data: m,
success: function(result) {
$("div#updatePane").html(result);
},
complete: function() {
$('form').onsubmit({ preventDefault: function() { } });
}
});
All of model's field must bo ceated in m.
In ajax call mention-
data:MakeModel(),
use the below function to bind data to model
function MakeModel() {
var MyModel = {};
MyModel.value = $('#input element id').val() or your value;
return JSON.stringify(MyModel);
}
Attach [HttpPost] attribute to your controller action
on POST this data will get available

Resources