I am creating an ASP.NET MVC application. I am currently developing a search page where both the search box and the table of results are displayed on the same page. To do this I have used Partial Views and AJAX/JSON calls with a viewmodel. After entering the two search terms in the textbox, both are null in the controller after being passed through ajax.
Here is the code:
ViewModel:
public class ExampleViewModel
{
public string search { get; set; }
public string search2 { get; set; }
}
Controller:
[HttpPost]
public ActionResult Search(ExampleViewModel searchTerm)
{
var searchList = db.UserLists.Where(x => x.LastName.Contains(searchTerm.search));
return PartialView("_SearchResultsPartial", searchList);
}
Body of Index View:
<body>
<div>
#Html.TextBoxFor(model => model.search)
#Html.TextBoxFor(model => model.search2)
<input type="submit" value="Search" onclick="return getSearchResults()"/>
</div>
<div id="search-results">
</div>
<script>
var exViewModel = {
search: $('#search').val(),
search2: $('#search2').val()
}
function getSearchResults() {
$.ajax({
type: "POST",
data: JSON.stringify(exViewModel),
dataType: "json",
contentType: "application/json",
url : "/View/Search/",
success: function (result) {
$("#search-results").html(result);
}
});
}
</script>
Again, after setting a breakpoint on the Search [POST] method, the ExampleViewModel's terms are null.
At first sight, it seems that you have to retrieve the values within the function scope:
function getSearchResults() {
//Read these values on button click
var exViewModel = {
search: $('#search').val(),
search2: $('#search2').val()
}
$.ajax({
type: "POST",
data: JSON.stringify(exViewModel),
dataType: "json",
contentType: "application/json",
url : "/View/Search/",
success: function (result) {
$("#search-results").html(result);
}
});
}
Otherwise, the exViewModel is just determined on page load.
Related
I tried to upload documents but I couldnt pass to list my controllers parameter. My scenario is:
user click to "choose file" button and pick the files and press done
then my some functions get file list and pass to controller for save locally via POST merhod like below:
view side: (get file list)
function saveDocuments(documentList) {
if (documentList.length > 0)
{
var formList = new Array;
for (var i = 0; i < documentList.length; i++) {
var form = new FormData();
var file = documentList[i];
form.append('FormFile', file);
formList.push(form);
}
savePhysicalFile(formList);
}
}
view side: (post file list)
function savePhysicalFile(formData)
{
if (formData != null)
{
$.ajax({
url: "Installation/SavePhysicalPath",
type: 'POST',
dataType: "json",
contentType: "multipart/form-data",
data:formData,
processData: false,
contentType: false,
success: function (result) {
console.log("Success", result);
},
error: function (data) {
console.log(data);
}
});
}
}
In my controller side; the parameter "model" is always null. I couldnt pass view side list here. How can I figure out ?
controller side
public JsonResult SavePhysicalPath([FromForm] List<FileModel> model)
{
var savingRootPath = #"C:\MyDocuments";
//I'm doing save locally
return Json(savingRootPath);
}
model side
public class FileModel
{
public string Files { get; set; }
public IFormFile FormFile { get; set; }
}
From your code,you may pay attention to two things here:
1.For each property of the complex type, model binding looks through the sources for the name pattern prefix.property_name. If nothing is found, it looks for just property_name without the prefix.For model you receive in backend is a List,you need give the name like:[index].FormFile or model[index].FormFile.
2.Your model has a IFormFile and your action receives a list model,if you only pass the IFormFile you need remove FromForm attribute and be sure do not have [ApiController].It is a known github issue and this has been moved to Next sprint planning milestone.
Here is a whole working demo:
View:
<input type="file" multiple onchange="saveDocuments(this.files)"/>
<div class="form-group">
<input type="button" value="Submit" id="submit" class="btn btn-primary" />
</div>
#section Scripts
{
<script>
function saveDocuments(documentList) {
if (documentList.length > 0) {
var form = new FormData();
for (var i = 0; i < documentList.length; i++) {
var file = documentList[i];
//change here
form.append('model['+i+'].FormFile', file);
}
savePhysicalFile(form);
}
}
function savePhysicalFile(formData) {
if (formData != null) {
$.ajax({
url: "/Installation/SavePhysicalPath",
type: 'POST',
dataType: "json",
contentType: "multipart/form-data",
data: formData,
processData: false,
contentType: false,
success: function (result) {
console.log("Success", result);
},
error: function (data) {
console.log(data);
}
});
}
}
</script>
}
Controller:
[HttpPost]
public JsonResult SavePhysicalPath(List<FileModel> model)
{
var savingRootPath = #"C:\MyDocuments";
//I'm doing save locally
return Json(savingRootPath);
}
Result:
I am trying to pass ID parameter from a view to a controller on a click delete link available on a selected row.
Simplified View Layout
#using (Html.BeginForm("#", "Schedule", FormMethod.Post, htmlAttributes: new { #class = "floating-labels" }))
{
#Html.AntiForgeryToken()
Delete
}
JavaScript
<script type="text/javascript">
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Schedule", new { id = "id" })',
contentType: "application/json",
data: { id },
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
Controller
namespace Controllers
{
public class ScheduleController
{
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
//do stuff
}
}
}
But on the click of a delete link I get below error and code does not hit controller action.
I am not able to figure out what mistake I am making...
Here is my locally tested implementation that is working.
ScheduleController class:
public class ScheduleController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Delete(int id)
{
return Ok(id);
}
}
Page that sends the post request:
#Html.AntiForgeryToken()
Delete
<div id="ScheduleList"></div>
<script>
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
var uri = '/Schedule/Delete?id=' + id;
var tokenElement = document.getElementsByName('__RequestVerificationToken')[0];
var data = {
__RequestVerificationToken: tokenElement.value
}
$.ajax({
type: "POST",
url: uri,
data: data,
success: function (result) {
success(result);
}
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
The page does nothing but render the html, and the javascript handles the actual Ajax post. What I believe you were missing is the Validation token in your request.
It is because you are not actullay posting the form pass it correctly and add _token in the ajax data list and value for that token will come from #Html.AntiforgeryToken()
reading the error the request is most probably send correctly and there is an internal server error as mentioned in the 500 respond so please check the code that is inside the controller
Try this, you are accesing a javascript variable on c# code, and you cant do that.
If correct, please mark as answer.
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
var url = '#Url.Action("Delete", "Schedule")?id=' + id;
$.ajax({
type: "POST",
url: url,
contentType: "application/json",
data: { id },
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
I think none of the answers above solve the issue. First of all I would replace your target url:
url: '#Url.Action("Delete", "Schedule", new { id = "id" })',
with
url: '#Url.Action("Delete", "Schedule", new { id = actualIdVariable })',
(replace "id" with the actual id variable from the model you're passing to the view).
Note how your browser response is telling you that the url you're posting to is Schedule/Delete/id. That said, I'm not sure you even need the routeValues in this case (the new { id = ...} parameter). this is a POST action, and action parameters wouldn't come from route unless specified by by attribute routing (i.e. [Route("~/Schedule/Delete/{id}")] attribute on your action).
I think your post action is failing because it is trying to parse the "id" string as an int.
Second, I would change the data property of the ajax call and include the anti forgery token. Just because the anchor element you're binding the click event to, is inside the form with #Html.AntiforgeryToken() doesn't mean the generated token will be posted in the ajax request. You're not actually submitting/posting the form, you're just clicking a button.
it should be something like
data: {
'id': id,
'__RequestVerificationToken': $('[name="__RequestVerificationToken"]').val()
}
try this, it solve the error on routing (different url Action) and the parameter on the controller:
JavaScript
<script type="text/javascript">
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Schedule")',
data: "id=" + id ,
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(string id)
{
//do stuff
}
Nicola.
So on button click there is a function sendEmail(). Alert is working fine, I can see my datas there. But on backend I can't see anything, just everything is null.
function sendEmail() {
var datas = new Object();
datas.mail = $('#contactDropdownList').val();
datas.mailobject = $('#emailObject').val();
datas.text = $('#emailText').val();enter code here
alert(datas.mail + datas.mailobject + datas.text);
$.ajax({
type: "POST",
dataType: "json",
url: "/Email/sendEmail",
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({ items: datas }),
success: function (data) {
console.log(data);
//do something with data
},
error: function (jqXHR, textStatus, error) {
//log or alert the error
console.log(error);
}
});
}
C# code:
public class MyClass
{
public string Email { get; set; }
public string Object { get; set; }
public string Text { get; set; }
}
[HttpPost]
public IActionResult sendEmail(MyClass items)
{
return Json(new { data="Ok" });
}
items.Email, items.Object and items.Text are null.
And the return valu is null as well, because in javascript success: function (data) { console.log(data);
is empty string.
What can be the problem? Thank you!
Model binder expects json content to match C# class. Your datas object should look like that
var datas = {
email: $('#contactDropdownList').val(),
object: $('#emailObject').val(),
text: $('#emailText').val()
}
Since you wrapped your object ({ items: datas }), you may think it will be mapped to sendEmail(MyClass items), but in reality items name does not matter, you can change variable name to any other name you like
Make sure you apply [FromBody] attribute to your parameter like that
[HttpPost]
public IActionResult sendEmail([FromBody]MyClass items)
Complete demo:
<script>
function sendSmth() {
var data = {
Email: 'email',
Object: 'object',
Text: 'text'
};
$.ajax({
type: "POST",
dataType: "json",
url: "/home/index",
contentType: "application/json",
data: JSON.stringify(data),
success: function (datas) {
console.log(datas)
}
})
}
</script>
And controller
[HttpPost]
public IActionResult Index([FromBody]MyClass obj)
{
return View();
}
As someone has noted, you have a mismatch between what you're sending to the controller and what the model the modelbinder is expecting. You can also vastly simply your AJAX code:
function sendEmail() {
var data = {
Email: $('#contactDropdownList').val(),
Object: $('#emailObject').val(),
Text: $('#emailText').val()
};
$.post("/Email/sendEmail", data)
.done(function (response) {
console.log(response);
//do something with response
})
.fail(function (jqXHR, textStatus, error) {
//log or alert the error
console.log(error);
});
}
You don't really need to specify the content type or data type - the $.post helper's defaults work just fine for what you've shown.
So I have a ViewModel that holds some basic information, and I am taking in an input from the view. Then the input is sent to a .js function that sends it to a controller function that does some work with it. Right now I am just trying to get the Javascript function to connect and display some irrelevant code on the page just to make sure its connected. I make it through everything with no errors, and at the very end I am returned the errorOnAjax Function, inside of the browser tools, that I have written myself. So there is no problem with any of the code that I can see.
My thought is, I am converting the ViewModel to Json wrong in the controller, in turn, it is returning it the wrong way to the Javascript function and giving the error. If anyone has any suggestions, it would be greatly appreciated!
public class MapInfoViewModel
{
public string Place { get; set; }
public string City { get; set; }
public string State { get; set; }
public string URL { get; set; }
}
And I am getting information from the view via an input box
#using (Html.BeginForm())
{
<input type="text" id="name" />
<button id="myButton" onclick="getInfo()">AJAX</button>
}
This is what my Javascript Function looks like. showInfo is just injecting a basic table into the view with just 1 value inside, just to make sure it is connected.
function getInfo(Info) {
var myInfo = document.getElementById('name').value;
$.ajax({
type: "GET",
dataType: "json",
url: "/CreateRoute/DisplayInfo",
data: { 'myInfo': myInfo },
success: showInfo,
error: errorOnAjax
})
}
and my Controller Function
public ActionResult DisplayInfo()
{
string request = Request.QueryString["myInfo"];
MapInfoViewModel info = new MapInfoViewModel()
{
Place = request
};
return new ContentResult
{
Content = JsonConvert.SerializeObject(info),
ContentType = "application/json",
ContentEncoding = System.Text.Encoding.UTF8
};
}
You wrote everything correct code but you just miss the one attribute in view.
you need to mention button type then it will work as per your expectations
<button id="myButton" onclick="getInfo()">AJAX</button>
Now I sharing the complete details of this issue.
Javascript-
function getInfo(Info) {
var myInfo = document.getElementById('name').value;
$.ajax({
type: "GET",
dataType: "json",
url: "/Test/DisplayInfo",
data: { 'myInfo': myInfo },
success: showInfo,
error: errorOnAjax
})
function showInfo(result) {
console.log(result);
}
function errorOnAjax() {
console.log("errorOnAjax");
}
}
View -
#using (#Html.BeginForm())
{
<input type="text" id="name" />
<button type="button" id="myButton" onclick="getInfo()">AJAX</button>
}
Controller-
public ActionResult DisplayInfo()
{
string request = Request.QueryString["myInfo"];
MapInfoViewModel info = new MapInfoViewModel()
{
Place = request
};
return new ContentResult
{
Content = JsonConvert.SerializeObject(info),
ContentType = "application/json",
ContentEncoding = System.Text.Encoding.UTF8
};
}
First return with json in controller.
public ActionResult DisplayInfo(string myInfo)
{
MapInfoViewModel info = new MapInfoViewModel()
{
Place = myInfo
};
return Json(info,JsonRequestBehavior.AllowGet);
}
In Front End use ajax like this.
$( "#myButton" ).click(function() {
let data={myInfo:$('#name').val();};
$.ajax({
type: "GET",
dataType: "json",
url: "/CreateRoute/DisplayInfo",
data: data,
success: function (response){
//do
},
error: function (error){
}
});
});
You need to create JsonResult function, then return Json(info, JsonRequestBehavior.AllowGet) as #sadullah zolfqar answered you.
Please refer to the below link to get the full explanation:
https://www.c-sharpcorner.com/UploadFile/2ed7ae/jsonresult-type-in-mvc/
I am using Asp.Net Core MVC. I am trying to post an object to action result using jquery http post. When I set my object with static values, i can see all fields are set properly on client side and backend. Posted object is not null.
When I set fields of request with jquery .val() method. Request object is sent as null to backend. Where am I making mistake ?
$("#saveReport").on("click", function () { //SENDS NULL OBJECT
var request = {
BookId: $("#cmbBook").val(),
PageCount: $("#txtPageCount").val(),
Date: $("#dateReport").val(),
Note: $("#txtNotes").val(),
};
//var request = { //SENDS OBJECT PROPERLY
// BookId: 1,
// PageCount: 10,
// Note: "test"
//};
$.ajax({
type: "POST",
url: appUrl + "Report/AddUserReport",
data: JSON.stringify(request),
success: function (data) {
},
error: function (data) {
},
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
And below is backend
[HttpPost]
public ActionResult<ReadingLogResponse> AddUserReport([FromBody]AddReportModel model)
{
var response = _reportBusiness.AddReport(new AddReadingLogRequest()
{
BookId = model.BookId,
Date = model.Date,
Note = model.Note,
PageCount = model.PageCount
});
return response;
}
jquery .val() method would set the data with string type by default.You need to parse Int.Here is a simple demo like below:
1.Model:
public class AddReportModel
{
public int BookId { get; set; }
public int PageCount { get; set; }
public DateTime Date { get; set; }
public string Note { get; set; }
}
2.View:
<form>
BookID:<input id="cmbBook" type="text" />
PageCount:<input id="txtPageCount" type="text" />
Date:<input id="dateReport" />
Notes:<input id="txtNotes" type="text" />
<input type="button" id="saveReport" value="post" />
</form>
#section Scripts
{
<script>
$("#saveReport").on("click", function () { //SENDS NULL OBJECT
var request = {
BookId: parseInt($("#cmbBook").val()),
PageCount: parseInt($("#txtPageCount").val()),
Date: $("#dateReport").val(),
Note: $("#txtNotes").val(),
};
console.log(request);
console.log(JSON.stringify(request));
$.ajax({
type: "POST",
url: appUrl + "Report/AddUserReport",
data: JSON.stringify(request),
success: function (data) {
},
error: function (data) {
},
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
</script>
}
3.Controller:
[HttpPost]
public ActionResult<ReadingLogResponse> AddUserReport([FromBody]AddReportModel model)
{
//...
}