Send multiple objects with jQuery to MVC 3 Controller - c#

I have a checkbox list and dropdown list. I want to pass selected value from dropdownlist and checked checkboxes to my MVC3 Controller and use model binding.
ViewModel for checkbox:
public class StateViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool Checked { get; set; }
public IEnumerable<TransitionViewModel> Transitions { get; set; }
}
Editor template for StateViewModel /Views/Home/EditorTemplates/StateViewModel.cshtml:
#model Mcs.Sibs.UI.Web.Models.StateViewModel
#Html.HiddenFor(x => x.Id)
#Html.HiddenFor(x => x.Name)
<div>
#Html.CheckBoxFor(x => x.Checked)
#Html.LabelFor(x => x.Checked, Model.Name)
</div>
My view:
#using (Html.BeginForm("GetSchedules", "Home", FormMethod.Post, new { id = "checkboxFrm" }))
{
#Html.EditorForModel()
<input id="ShowReportScheduleBtn" type="button" value="Show schedule" onclick="ShowReportSchedules()" />
}
Button click handler which is sending data to controller:
function ShowReportSchedules() {
var selectedGenerationId = $('#SelectedGenerationId').val();
var statesData = JSON.stringify($('#checkboxFrm'));
var statesData2 = $('#checkboxFrm').serialize(); //I also tried this
$.ajax({
type: 'POST',
url: '/Home/GetSchedules',
data: { "generationId": selectedGenerationId, "states": statesData },
dataType: "json",
contentType: 'application/json; charset=utf-8'
});
};
Finally, my controller:
[HttpPost]
public ActionResult GetSchedules(int generationId, IEnumerable<StateViewModel> states)
{
return View("Index");
I can't pass values to my controller. I've managed to pass only statesData object without jQuery and using type="submit" in my form. When I tried to pass only statesData with jQuery and type="button" I got "Invalid JSON primitive" error in FireBug.
When I tried to pass integer + statesData object, IE 9 is crashing and Firefox hangs.
I've tried various solutions but without success.

Try like this:
function ShowReportSchedules() {
var selectedGenerationId = $('#SelectedGenerationId').val();
$.ajax({
type: 'POST',
url: '#Url.Action("getschedules", "home")?generationId=' + selectedGenerationId,
data: { states: $('#checkboxFrm').serialize() },
success: function(result) {
// Do something with the results
}
});
};

var a = $("#a").serialize();
var b = $("#b").serialize();
var c = $("#c").serialize();
$.ajax({
url: '#Url.Content("~/Controller/Method1")',
type: 'POST',
data: a+b+c,
success: function (success) {
// do something
}
});
// in Controller
[HttpPost]
public ActionResult Method1(abc a, bcd b, xyz c)
{
}
// where abc, bcd xyz are class

Related

Cannot pass list of objects from view to controller by Ajax

I cannot pass a list of objects to a controller via Ajax.
However my code is simple :
Here is the object class :
public class OptionDTO
{
public string ID_OPTION { get; set; }
public string LI_VALUE { get; set; }
}
Here is my view :
<div class="col-lg-12 col-md-12 col-xs-12" id="divOption">
<table id="TableOption">
#foreach (var item in Model)
{
<tr class="item">
<td>#item.LI_OPTION</td>
<td>
<input type="text" class="option-value" data-id="#item.ID_OPTION" />
</td>
</tr>
}
</table>
<script>
function fctValidate() {
var lstOption = [];
try
{
$(".option-value").each(function(){
var oOption = new Object();
oOption.ID_OPTION = $(this).attr('data-id');
oOption.LI_VALUE = $(this).val();
lstOption.push(oOption);
});
} catch (error) {
alert(error);
}
$.ajax({
type: "POST",
traditional: true,
url: '#Url.Action("CreateOption", "CreateOption")',
data: { "lstOption": lstOption },
dataType: "json",
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
and here is the controller:
[HttpPost]
public void CreateOption(List<OptionDTO> lstOption)
{
string dd = "";
}
I fill the input "text" with values (several rows in the table).
I have checked in the javascript that the list contains several rows.
And when I click on the Validation button the code goes to the controller but the parameter lstOption remains empty.
Could you help me, please ?
Thanks a lot in advance.
Eric.
derloopkat, Dawood Awan :
Thanks to your advices, I finally have the solution which works :
function fctValidate() {
var lstOption = [];
try {
$(".option-value").each(function () {
lstOption.push({
ID_OPTION: $(this).data('id'),
LI_VALUE: $(this).val()
});
});
} catch (error) {
alert(error);
}
$.ajax({
type: "POST",
url: '#Url.Action("CreateOption", "CreateOption")',
data: { 'lstOption': lstOption },
dataType: "json",
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}

How to assign return value from json into a textbox?

I have a dropdown list of Tests(Diagnostic) on my view and selecting any Test from that list it should load corresponding Fee into a readonly textbox.
Here is my View:
<select name="TestId" id="TestId" style="width: 171px;">
<option value="">Select...</option>
#foreach (var tests in ViewBag.allTests)
{
<option value="#tests.TestId">#tests.TestName</option>
}
</select>
<input type="text" id="TestFee" name="TestFee" readonly="readonly" />
<script>
$(document).ready(function() {
$("#TestId").change(function() {
var testid = $("#TestId").val();
//$("#fees").empty();
var json = { testId: testid };
$.ajax({
type: "POST",
url: '#Url.Action("GetFeesById", "TestRequest")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function(data) {
$("#TestFee").val(data.Fee);
}
});
});
});
And there is controller:
public class TestRequestController : Controller
{
SaveTestManager manager=new SaveTestManager();
public ActionResult SaveTestRequest()
{
ViewBag.allTests = manager.AllTestViews();
return View();
}
[HttpPost]
public JsonResult GetFeesById(int testId)
{
var testlist = manager.AllTestViews().Where(m => testId==m.TestId);
return Json(testlist, JsonRequestBehavior.AllowGet);
}
}
I used Debugger on my JsonResult, It returns corresponding Data on change of dropdown item. But, my textbox does not get Fee which returned from controller.
Is there any wrong with this code? how could be assign value on textbox?
NB: I never Used Json before, I just trying with the help of some blogs and tutorials. If is there any better way please suggest this as well.
Thanks
Try this
$("#TestFee").val(data.data[0].Fee);

Issue while calling action method with ajax contentType

I have an application that need to post back through Ajax. Getting problem while calling the ActionMethod. below are the code.
Controller :
[HttpGet]
public ActionResult Index()
{
return View();
}
public JsonResult AjaxTest(object name)
{
return Json("Welcome" + name, JsonRequestBehavior.AllowGet);
}
Cstml :
<form name="frmTest" method="POST">
#Html.Label("Your name Please")
#Html.TextBox("username")
<input class="btn btn-success btn-lg btn-block" type="submit" value="Login">
JQuery :
$(function () {
$("form[name='frmTest']").submit(function (e) {
var name = $('#username').val();
$.ajax(
{
type: "POST",
//contentType: "application/json; charset=utf-8",
url: "MyTest/AjaxTest",
dataType: "json",
data: { name:name },
success: function (data, status) {
alert("Pass"+data);
},
error: function () {
alert("Fail");
}
});
});
});
By using the above code break point hit to AjaxTest with the parameter. when I use contentType: "application/json; charset=utf-8", then the page postedback without hitting the break point.
But both cases I got fail alert. unable to find the issue,
I am not sure what you are trying to do but since in one of the comments you stated you will be saving stuff to the database, normally, in ASP MVC it would be done like this.
Create a class for whatever you will be posting using AJAX. For example, in this example, I created a class called Person
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Then in your form you can have something like this:
#{
ViewBag.Title = "Test";
}
<form name="frmTest" method="POST">
#Html.Label("Your name Please")
#Html.TextBox("username")
<input class="btn btn-success btn-lg btn-block" type="submit" value="Login">
</form>
<script>
$(function () {
$("form[name='frmTest']").submit(function (e) {
var name = $('#username').val();
$.ajax(
{
type: "POST",
//contentType: "application/json; charset=utf-8",
url: "AjaxTest",
dataType: "json",
data: { "Age": 55, "Name": name },
success: function (data, status) {
alert("Pass" + data);
},
error: function (ex) {
alert("Fail" + ex);
}
});
});
});
</script>
Then have an action which the JSON will be submitted to. For the above, the action will be like this:
public JsonResult AjaxTest(Person person)
{
return Json("Welcome" + person.Name, JsonRequestBehavior.AllowGet);
}
ASP MVC will take care of the binding for you. Please also note the url I am posting is "AjaxTest" and it will post to AjaxTest action method of the controller which served the form.
If you have a controller like below, then all of the above will work.
public class AccountController : Controller
{
// This returns the view with the form
public ActionResult Test()
{
return View();
}
public JsonResult AjaxTest(Person person)
{
return Json("Welcome" + person.Name, JsonRequestBehavior.AllowGet);
}
}

Knock Out Js - Unable to set default item, when Select Item initialized with Ajax

My View is as below:
function event(EventType) {
this.EventType = ko.observable(EventType)
}
My View Model is as below:
function eventListViewModel(EventType) {
self = this;
self.Events = ko.observable(EventType)
self.eventtypes= ko.observableArray([]);
$.ajax({
url: "../GetEventTypes/",
type: "post",
contentType: "application/json",
async: true,
cache: true,
success: function (data) {
var array = [];
$.each(data, function (index, value) {
array.push(value);
});
self.eventtypes(array);
}
});
}
Now I have initialized my view model as below:
$(function () {
$.ajax({
url: "#Url.Action("GetExistingEvents", new { Id = Model.Id})",
type: "POST",
data: {},
success: function (data) {
//var events = ko.toJSON();
vm = new eventListViewModel(data);
ko.applyBindings(vm);
}
});
});
And the above Action will return List of Below Event class in json Format:
public class Event
{
public int Id {get;set;}
public int Name {get;set;}
}
Public JsonResult GetExistingEvents()
{
List<Event> evnt = new List<Event>();
evnt.Add(new Event {Id : 1 , Name : "Test"});
return new Json(evnt );
}
Now my drop down knock out binding is as below which binds EventTypes :
<div data-bind="foreach: Events ">
<select id="" class=" form-control col-md-8" data-bind="
options: $root.eventtypes,optionsText: 'Name', optionsValue: 'Id',selectedOptions: $data.EventType, optionsCaption: '--Please select an item --'"></select>
</div>
Now, My problem is I m not able to set the selected option, PLease help me out whats wrong with the above code ?

How to send javascript dictionary to controller method in MVC4

I have a js file that has to send a dictionary object to the server. My javascript part looks like that:
$.ajax({
url: "/ControllerName/ActionName",
type: 'post',
dataType: 'json',
data: myData
});
where myData is something like
this myData["favouritePet"] = "dog", myData["favouriteBook"] = "What?"
In the controller I have this:
[HttpPost]
public virtual ActionResult ActionName ( Dictionary<string, string> jsonFormattedData)
{
return null;
}
but when I debug it the parameter gets a null value every time. I tried to make the argument of type string but it is the same. Can you help me with that?
You are just passing JavaScript object, so you can use JSON.stringify and make the Model as Action parameter.
MVC Model Binder will convert it to your model.
public class MyDataModel
{
public string FavouritePet { get; set; }
public string FavouriteBook { get; set; }
}
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(MyDataModel myData)
{
return View();
}
<button id="btnSubmit" type="button">Submit</button>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$("#btnSubmit").click(function () {
var myData = new Object();
myData.favouritePet = "dog";
myData.favouriteBook = "What?";
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'POST',
dataType: 'json',
data: JSON.stringify(myData),
contentType: "application/json; charset=utf-8",
success: function (){}
});
});
</script>

Categories

Resources