Ajax post model to controller on submit - ajax

I have a model class
public class ViewModel
{
public HttpPostedFileBase File {get;set;}
public string FileName {get;set;}
}
Controller
[HttpPost]
public ActionResult Upload(ViewModel model)
{
}
VIEW
$("#myform").on("submit", function (event) {
event.preventDefault();
var formData = {
FileName: $('#fileName').val(),
File: $('#file').get(0).files[0],
};
$.ajax({
url: url,
type: "POST",
data: formData,
contentType:"multipart/form-data",
success: function (resp) {
}
});
I am not able to post my model to the controller? What am i doing wrong?

Related

Accessing of Web API response object in another partial view (cshtml / cshtml.cs file) in Visual Studio 2022

On click of a button will from a partialview 1 below js function will be called and get the data from the controller and will be redirected to another partialview. Since it the controller is in another project and hosted separately, controller is not returning the partialview hence I am redirecting it if the ajax call is success.
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(paramObj),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
var userObject = response.internalObject;
window.location.href = url2;
},
error: function (response, status, error) {
if (response.responseText != undefined) {
const obj = JSON.parse(response.responseText);
fnShowMessage(obj.DisplayMessage);
}
}
});
I have the data in "userObject" from the ajax call which needs to be displayed in partialview, but I cannot access it or not sure how to access it.
The assigned value in OnGet() method in "partialview2.cshtml.cs" is able to retain in "partialview2.cshtml" file. But how to get the values which I got from the ajax call in partialview 1 in code behind of partialview 2.
public class UserModel : PageModel
{
[BindProperty]
public UserObject UserObject { get; set; } = new();
public void OnGet()
{
UserObject.UserName = "man";
}
}
You can try to return JsonResult in OnGet:
ajax:
$.ajax({
type: "POST",
url: "/Home/Test",
data: JSON.stringify(paramObj),
contentType: "application/json; charset=utf-8",
traditional: true,
dataType: "json",
success: function (response) {
var userObject = response;
window.location.href = url2;
},
error: function (response, status, error) {
if (response.responseText != undefined) {
const obj = JSON.parse(response.responseText);
fnShowMessage(obj.DisplayMessage);
}
}
});
OnGet handler:
public class UserModel : PageModel
{
[BindProperty]
public UserObject UserObject { get; set; } = new();
public JsonResult OnGet()
{
UserObject.UserName = "man";
return new JsonResult(UserObject);
}
}

send complex and simple parameter to web api using ajax

i write web api.
web api controller:
public class TaskApiController : ApiController
{
[HttpPost]
public IHttpActionResult PostNewTask(string xx,string yy,CommonTask Task)
{
...
}
}
and ajax:
var task = new Object();
task.Description = 'kjk';
task.ID = null;
var req = $.ajax({
url: 'http://localhost:3641/api/TaskApi',
contentType: "application/json",
data: {"xx":'admin',"yy":'123',"task": JSON.stringify(task) },
type: 'Post',
success: function (data) {
alert('success');
}
});
req.fail(function (jqXHR, textStatus) {
alert("Request failed: " + jqXHR.responseText);
});
and WebApiConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
when run ajax, return error:
No action was found on the controller 'TaskApi' that matches the request
Always feed the POST methods with class type parameters. Please do the following modification on the API and JavaScript.
1. Create a model class
<pre>
public class Model
{
public string xx { get; set; }
public string yy { get; set; }
public CommonTask Task { get; set; }
}
</pre>
Then modify your Web API to accept a type of your class model
<pre>
public class TaskApiController : ApiController
{
[HttpPost]
public IHttpActionResult PostNewTask([FromBody] Model model)
{
}
}
</pre>
Change your ajax method to pass a json object similar to the Model class
<pre>
var task = new Object();
task.Description = 'kjk';
task.ID = null;
var data = {
"xx": 'admin',
"yy": '123',
"task" : JSON.stringify(task)
};
var req = $.ajax({
url: 'http://localhost:3641/api/TaskApi',
contentType: "application/json",
data: {"model": JSON.stringify(data) },
type: 'Post',
success: function (message) {
alert('success');
}
});
req.fail(function (jqXHR, textStatus) {
alert("Request failed: " + jqXHR.responseText);
});
</pre>

Json post to MVC controller with Parameters

Can't seems to figure out why this is not working. I can't get the parameters to post to MVC controller method:
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<input id="Button1" type="button" value="button" onclick="CallMethodone()" />
<div id="result"></div>
<script>
function CallMethodone() {
var detailsURL = '/Testdrive/Methodone';
var request = {
'parameterOne': "test one",
'parameterTwo': "test two"
};
$.ajax({
url: detailsURL,
contentType: "applicaton/json",
type: "POST",
data: JSON.stringify(request),
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(response, status) {
//alert(data + " " + status);
$("#result").text(response.result);
}
function errorFunc(xhr, status) {
alert("error");
}
}
</script>
And my controller method is like this:
[HttpPost]
[AllowAnonymous]
public ActionResult Methodone(string parameterOne, string parameterTwo)
{
return View();
}
parameterOne or parameterTwo do not have any values in them.
UPDATE:
You should create a class for the parameters, try this:
[Serializable]
public class Your_Class_Name {
public string parameterOne {get; set;}
public string parameterTwo {get; set;}
}
At the Controller:
[HttpPost]
[AllowAnonymous]
public ActionResult Methodone(Your_Class_Name parameters)
{
// Badass code here
}
Hope it works =D
you can do the following
var parameterOne = 'test one';
var parameterTwo = 'test two';
$.ajax({
url: '/Testdrive/Methodone?parameterOne='+parameterOne+'&parameterTwo='+parameterTwo,
contentType: "applicaton/json",
type: "POST",
success: successFunc,
error: errorFunc
});
or try this:
In code: data: JSON.stringify(request)... remove JSON.stringify,
Should look like:
data: request,
Another detail is its object.
var request = {
'parameterOne', "one test"
'parameterTwo': "test two"
};
In it you put 2 parameter, then in its method you have to get two also.
public ActionResult Method (String parameterOne, String parameterTwo)
{
return View ();
}
Look at the result:
http://tinypic.com/r/r0t2z8/8

Pass serialized form to Action and bind to model

I am trying to bind model received from Ajax call but that do not work. Maybe someone could help me?
I am calling ValidateFile Action using Ajax
$.ajax({
url: '#Url.Action("ValidateFile", "Converter")',
data: ({ file: fileName, formData: serializedForm }),
type: 'POST',
success: function (response) {
if (response.result) {
} else {
RemoveFile(fileName);
}
}
});
The Fiddler show such query
file=!!!SP+Design!!!.txt&formData%5BEmail%5D=tomas%40mydomain.com
I receive data in my Action with file parameter populated but formData.Email property is always Null
[HttpPost]
public JsonResult ValidateFile(string file, UploadOptionModel formData)
{
}
My UploadOptionModel model
namespace PC.Models
{
public class UploadOptionModel
{
public string Email { get; set; }
}
}
Form which I am trying to serialize
#model PC.Models.UploadOptionModel
#using (Html.BeginForm())
{
#Html.EditorFor(p => p.Email)
}
JS Serialization function
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;
}
You need to JSON encode the data and set the content type to JSON for the model binder to work with JSON. So try this:
$.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);
}
}
});

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)
{
...
}
}

Resources