Post Model to Controller in ajax - ajax

This is My ajax Code
$('#RolesSave').click(function () {
var sRow = JSON.parse(JSON.stringify($('#table').bootstrapTable('getSelections')));
var ID = JSON.stringify(sRow, ["ID"]);
var view = {
CompanyCode: $('#Company').val(),
RolesCode: $('#Roles').val(),
ID,
};
$.ajax({
method: "POST",
url: '#Url.Action("Save")',
data: $('#formData').serialize(),
success: function (data) {
alert(data + '!!!')
},
error: function () {
alert('ERROR')
}
})
})
This is My Controller
[HttpPost]
public IActionResult Save(RightsModel view)
{
return View();
}
and This My Model
public class RightsModel
{
public List<string> ID { get; set; }
public string Company { get; set; }
public string Roles { get; set; }
}
and this is my view
<form id="formData">
#Html.DropDownListFor(m => m.Company, Model.Company)
#Html.DropDownListFor(m => m.Roles, Model.Roles)
<button id="RolesSave" class="btn btn-primary btn-light" type="submit">存檔</button>
<table id="table"></table>
My problem is when I use the code $('#formData').serialize(). It can convert the data in View into Model normally.
But when I use JSON.serialize(view), It can't achieve the same goal.
Even if I add [FormBody] to the Action, I cannot get any relevant information.
Any suggestions?

JSON.serialize is not exists in js,we usually use JSON.stringify.And you need to make sure the model structure of view is the same with model RightsModel.And you need to add contentType:"application/json", to ajax since you want to pass json type data to action.Here is a demo:
js:
$('#RolesSave').click(function () {
var sRow = JSON.parse(JSON.stringify($('#table').bootstrapTable('getSelections')));
var ID = [];
sRow.forEach(function (item, index) {
ID.push(""+item.ID);
});
var view = {
Company: $('#Company').val(),
Roles: $('#Roles').val(),
ID: ID
};
$.ajax({
method: "POST",
url: '#Url.Action("Save")',
data: JSON.stringify(view),
contentType:"application/json",
success: function (data) {
alert(data + '!!!')
},
error: function () {
alert('ERROR')
}
})
})
action:
[HttpPost]
public IActionResult Save([FromBody]RightsModel view)
{
return View();
}
result:
I try yo use var ID = ["1", "2", "3"]; to test,and it can work.ID need to be type List<string>.

Related

How to pass dictionary item from client side (Ajax) to server side (MVC API)

I want to pass multiple key and value pair of dictionary type from client side using post method to server side which is MVC Web API HTTP get method.
function FileSenderAPI(){
var DictionaryData = new Object;
DictionaryData = document.getElementById("hidFilePath").value;
var Url = '<%=System.Configuration.ConfigurationManager.AppSettings["FileSenderAPI"].To String() %>';
$.ajax({
url: Url,
method: 'Get',
data Type: "json",
data: {
ModelsPath:JSON.stringify(DictionaryData),
Exchange: exchange,
Exchange_key: key,
},
success: function (data, textStatus, xhr) {
alert(data);
},
}
public HttpResponseMessage ConvertModel(Dictionary<string, string> ModelsPath,string Exchange,string Exchange_key)
{
} // its my API method.``
Here is a solution. You can try it. Hope to help, my friend :))
1) Create a model
public class DictionaryModel
{
public Dictionary<string, string> dict { get; set; }
public string Exchange { get; set; }
public string Exchange_Key { get; set; }
}
2) Action
[HttpPost]
public JsonResult Example(DictionaryModel model)
{
// Your Logic
return Json("Success");
}
3) In View
$('#btClick').on('click', function () {
var dict = {};
dict["id"] = "200";
dict["Name"] = "Chris";
dict["DynamicItem1"] = "Item 1";
var theObject = {};
theObject.dict = dict;
theObject.Exchange = "Abc";
theObject.Exchange_Key = "123";
let url = '#Url.Action("Example","Home")';
$.post( url, theObject, function (data, textStatus, XMLHttpRequest) {
console.log("success");
}, "json");
});

call to function from the controller in index.html

In my mvc app I have combobox, I am trying to do the following: when the user choose some item that will call to some function from the controller.
Index.html:
#using (Ajax.BeginForm("dor", "Home", new AjaxOptions
{
HttpMethod = "Get",
//UpdateTargetId = "myPic",
InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace
}))
{
#Html.DropDownListFor(x => x.SelectedFileName, Model.Files, new { Name = "map", #class = "form-control", onchange = "CallChangefunc()" })
}
.
.
.
<script type="text/javascript">
function CallChangefunc() {
window.location.href = '#Url.Action("dor","Home")';
}
</script>
HomeVM:
public class HomeVM
{
public List<SelectListItem> Files { get; set; }
public string SelectedFileName { get; internal set; }
public List<string> DynamicAlgorithems { get; set; }
}
Homecontroller:
public void dor()
{
//some code
}
The problem: when the user choose some item from combobox it redirect me to blank page i.e to http://localhost:55354/Home/dor, but I only want to call the function named dor, not to go to blank page!.
what am I missing?
Related
window.location.href always redirect to a new page URL assigned to it. You should use jQuery.ajax() to call the action method when onchange method triggered and return desired result:
jQuery (inside $(document).ready())
$('#SelectedFileName').change(function() {
var selectedFileName = $(this).val();
$.ajax({
type: 'GET',
url: '#Url.Action("Dor", "Home")',
data: { fileName: selectedFileName },
success: function (result) {
// do something
}
});
});
Controller
[HttpGet]
public ActionResult Dor(string fileName)
{
// do something
}
Note: Make sure that action method argument has same name with assigned data passed from AJAX callback.

Serialize SelectListItem and binding

I have model
public class UploadOptionModel
{
public UploadOptionModel()
{
OutputFormat = outputFormatList.Select(i => new SelectListItem
{
Text = i,
Value = i
});
}
public string Email { get; set; }
public IEnumerable<SelectListItem> OutputFormat { get; set; }
}
and View
#model PC.Models.UploadOptionModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(p => p.Email)
#Html.DropDownList("OutputFormat", Model.OutputFormat)
}
I am trying to submit the form above using Ajax call and bind it to model
//Calling ValidateFile Action controller
$.ajax({
url: '#Url.Action("ValidateFile", "Converter")',
data: JSON.stringify({ file: fileName, formData: serializedForm }),
contentType: 'application/json',
type: 'POST',
success: function (response) {
if (response.result) {
} else {
RemoveFile(fileName);
}
}
});
function serializeForm() {
var data = $("form").serializeArray();
var formData = {};
for (var i = 0; i < data.length; i++) {
formData[data[i].name] = data[i].value;
}
return formData;
}
The ValidateFile action
[HttpPost]
public JsonResult ValidateFile(string file, UploadOptionModel formData)
{
}
The problem is that UploadOptionModel.OutputFormat is not binding. I can't read selected dropdown value. UploadOptionModel.Email field is bind successfully.
You should have another property in your Model class, where you bind the selected value of the dropdownlist.
So in your model add something like
public string OutputFormatSelected { get; set; }
And then use it in your view, this way:
#model PC.Models.UploadOptionModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(p => p.Email)
#Html.DropDownListFor( m => m.OutputFormatSelected, m.OutputFormat)
}
Your problem was that you wee binding both the list of elements and the result to the same property

MVC3 Ajax Get String and post it back

on MVC3 Page load i have a String in a Model which is should be the JSONObj.
private string CreateJSONObj(Model model)
{ return "{ name: 'test', Items: [{ test: 1 }, { test: 2 }]"; }
Model.jsonModel = CreateJSONObj(model);
Now i want to implement it in my page:
<script>var jsModel = eval('#Model.jsonModel');
var jsonModel = $.toJSON(jsModel);
$.ajax({
url: 'Page/SetJSON/',
type: "POST",
data: jsonModel,
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function () {
$('#test').html('Saved').fadeIn(),
},
error: function () {
$("#test").html("error"),
}
});</script>
But the Controller gets a null Object. If i write the jsonstring into the script everthing is fine.
Should i use eval? But var jsModel = eval('#Model.jsonModel'); has no effect. What is wrong? :-)
You don't need to use a CreateJSONObj method or a jsonModel property on your model. In order to use it in the view you could simply use the JavaScriptSerializer class which will convert the server side model object into a javascript object:
<script type="text/javascript">
var jsModel = #Html.Raw(new JavaScriptSerializer().Serialize(Model));
$.ajax({
url: '#Url.Action("SetJSON", "Page")',
type: 'POST',
data: JSON.stringify(jsModel),
contentType: 'application/json; charset=utf-8',
success: function () {
$('#test').html('Saved').fadeIn();
},
error: function () {
$('#test').html('error');
}
});
</script>
This will successfully send the model to the following controller action:
[HttpPost]
public ActionResult SetJSON(Model model)
{
...
}
where the Model class contains all the necessary information:
public class Model
{
public string Name { get; set; }
public IEnumerable<Item> Items { get; set; }
}
public class Item
{
public int Test { get; set; }
}
and the controller:
public class PageController: Controller
{
// Used to render the view
public class Index()
{
var model = new Model
{
Name = "Test",
Items = new[]
{
new Item { Test = 1 },
new Item { Test = 2 },
}
};
return View(model);
}
// Used to handle the AJAX POST request
[HttpPost]
public ActionResult SetJSON(Model model)
{
...
}
}

How to use ajax call to pass json data to controller and render a partial view as result?

I need to pass model object to controller, and from there to call service to generate data for the partial view. I am able to pass the json object to the main view, and I am able to generate the partial view. However, I am having difficulties to render the partial view in the main view after the call. If I don't pass object to controller, I am able to render the partial view.
My Main goal is: to pass json object and render partial view with the same ajax call.
Would appreciate help on this.
I apologize for the lengthy code here, but not sure how I could do it some other way.
The following code works, where I do not pass Json object via ajax call, and create department object in the controller:
main view code:
#model PartialViewDemo.Models.School
....
<body>
....
<div>
#Html.Partial("_MyPartialView", Model.Department )
</div>
....
<div id="divTest"></div>
<input type="button" value="Click" id="btnClick"/>
</body>
<script src="~/Content/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function() {
$('#btnClick').click(function(data) {
var dept = {
DepartmentName: "test Dept",
DepartmentRule: "test rule",
Comment:" test comment"
};
$.ajax({
url: '/home/ShowPartailView/',
success: function (result) {
$('#divTest').html(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
});
});
</script>
controller code:
public ActionResult Index()
{
var model = new School();
model.Department = GetDepartmentList(3);
return View(model);
}
public List<Department> GetDepartmentList(int counter)
{
var model = new List<Department>();
for (var i = 1; i <= counter; i++)
{
var data = new Department();
data.DepartmentName = "Dept " + i;
data.DepartmentRule = "Rule " + i;
data.Comment = "Comment " + i;
model.Add(data);
}
return model;
}
public PartialViewResult ShowPartailView()
{
Department dept = new Department()
{
DepartmentName = "test Dept",
DepartmentRule = "test rule",
Comment = "We Rock!"
};
PartialViewResult result = PartialView("_MySecondPartialView", dept);
return result;
}
Partial view code:
#model PartialViewDemo.Models.Department
<h2>_MyView from partial view using PartialView</h2>
#if (Model != null)
{
<div>
<table>
<thead>
....
</thead>
<tbody>
<tr>
<td>#Model.DepartmentName</td>
<td>#Model.DepartmentRule</td>
<td>#Model.Comment</td>
</tr>
</tbody>
</table>
</div>
}
Model:
public class Department
{
public string DepartmentName { get; set; }
public string DepartmentRule { get; set; }
public string Comment { get; set; }
}
public class School
{
public List<Department> Department { get; set; }
}
However, when I pass in Json object to ajax call with all other code stay the same, except the following changes, the partial view won't show with click event.
$.ajax({
url: '/home/ShowPartailView/',
data: JSON.stringify(dept),
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('#divTest').html(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
with controller code:
public PartialViewResult ShowPartailView(Department dept)
{
PartialViewResult result = PartialView("_MySecondPartialView", dept);
return result;
}
In the second example where you pass the object, you have specified the
dataType: 'json',
ajax option but your controller method is returning a partial view so it needs to be
dataType: 'html',
Side note: You can omit the contentType option and just use data: dept,
If you have return partial view then try this to render partial view in Div or any other element.
$(document).ready(function () {
$.ajax({
url: '/YourContollerName/YourActionName',
type: "POST"
})
.success(function (result) {
$('.loadOnDivClass').empty();
$('.loadOnDivClass').html(result);
})
.error(function (status) {
alert(status);
})
});
If Contrller Action return like this
return PartialView("_PartialList",modelObj);

Resources