Send string from View to Controller ASP.Net mvc - asp.net

So we are pretty new to ASP.Net MVC
We have this method that runs when we click on a button in our view. We would like to send the date string to our controller. How can we achieve this?
$('#calendar').fullCalendar({
//weekends : false
dayClick: function(date) {
console.log(date.format());
}
})
This is our controller
[HttpPost]
public IActionResult Booking(string test)
{
var booking = new Booking();
//booking.Date = dateTime;
Console.WriteLine(test);
var viewModel = new BookingsideViewModel
{
Subjects = new[] {"Matematik", "Dansk", "Engelsk"},
Booking = booking
};
return View();
}

you can do it using ajax call,
$.ajax({
url: '#Url.Action("Booking")',
data: { 'test' : date },
type: "post",
cache: false,
success: function (response) {
console.log("success");
},
error: function (error) {
console.log(error.message);
}
});
you can also write url like this:
url:"/ControllerName/ActionName"

Related

jQuery function not getting called in mvc text-changed event

I am getting this strange behavior in jQuery when working with mvc application.
Below is MVC view in which I have implemented Text change event,
#Html.TextBoxFor(m => m.UserId, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.UserId, "", new { #class = "text-danger" })
$("#UserId").change(function () {
var UserId = $(this).val();
//$("#txtName").val(emailId);
$.ajax({
url: 'GetValidUserName',
type: 'POST',
data: JSON.stringify({ UserId: UserId }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
if (!$.trim(data)) {
alert("User does not exist in system. Please enter valid User Id.");
$(':input[type="submit"]').prop('disabled', true);
}
else {
$("#UserId").val(data);
$("#UserId").focus();
$(':input[type="submit"]').prop('disabled', false);
}
}
});
});
While debugging application when I load Index view directly first time , jQuery function gets called and invoke the controller action properly.http://localhost:51012/UserApplication/Index
But when I load the view again, jQuery function doesn't get called.
Controller code,
public JsonResult GetValidUserName(string userId)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
string UserID = "";
objLMT.UserList = objLMTDAL.GetAll_User("", 0, "6");
var AllUsersInDatabase = from p in objLMT.UserList
where p.UserId == userId
select new
{
Name = p.UserName,
Id = p.UserId,
};
foreach (var user in AllUsersInDatabase)
{
if (user.Name != null)
{
UserID = user.Id;
}
}
return Json(UserID, JsonRequestBehavior.AllowGet);
}
You have several issues with AJAX callback:
1) type: 'POST' option requires [HttpPost] attribute. If the attribute isn't present on the action method, use type: 'GET' instead.
2) You don't need JSON.stringify() to pass single parameter containing simple types (numeric and string values). A simple { userId: UserId } should be fine.
3) The controller action's parameter name must be exactly match with parameter name sent from AJAX callback.
Therefore, your AJAX callback should be follow example below:
$(function () {
$("#UserId").change(function () {
var UserId = $(this).val();
$.ajax({
url: '#Url.Action("GetValidUserName", "ControllerName")',
type: 'GET',
data: { userId: UserId },
dataType: 'json',
success: function (data) {
if (!$.trim(data)) {
alert("User does not exist in system. Please enter valid User Id.");
$(':input[type="submit"]').prop('disabled', true);
}
else {
$("#UserId").val(data);
$("#UserId").focus();
$(':input[type="submit"]').prop('disabled', false);
}
}
});
});
});

Ajax call not passing arrays to controller action

I am passing an array variable to the controller.
Array from ajax call contains data but after calling the controller it shows count=0.
var url = '#Url.Action("UserRoleCompany_AddUserAccess", "UserRoleCompany")';
$.ajax({
url: url,
data: { userIDs: userIDs, Organisation: Organisation, RoleName: RoleName, userIDsLength: userIDsLength, UserStatus: UserStatus },
cache: false,
type: "POST",
success: function (data) {
location.reload(true);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
Controller code below,
public ActionResult UserRoleCompany_AddUserAccess(List<int> userIDs, string Organisation, string RoleName, int userIDsLength,int UserStatus)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
objLMTDAL.UserRoleCompany_AddUserAccess(Organisation, RoleName, userIDsLength, UserStatus);
return RedirectToAction("Index");
}
And below are a screenshot for reference,
You can not pass an array as a parameter in ajax,you can either convert userIDs to a json string or combine them as a string,then pass to the controller side.
More details information can be found at Why the array will not send through the ajax call?
#lucumt
I have tried the same thing with table - selecting the multiple rows from the table and send it to the controller and it is working fine.
Please check below and let me know.
var url = '#Url.Action("UserRoleCompany_UpdateUserAccess", "UserRoleCompany")';
$.ajax({
url: url,
data: { Ids: checkedIds, newUserStatus: UserStatus },
cache: false,
type: "POST",
success: function (data) {
location.reload(true);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
Controller
public ActionResult UserRoleCompany_UpdateUserAccess(List<int> Ids, int newUserStatus)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
string userRoleIds = String.Join(",", Ids);
objLMTDAL.UserRoleCompany_UpdateUserAccess(userRoleIds, newUserStatus);
return RedirectToAction("Index");
//return RedirectToAction("Index", "UserRoleCompany");
}
You can check the live scenario below in screenshots,

AJAX data parse to Controller and return back

Here is an AJAX call to the controller:
$.ajax({
type: "GET",
url: '#Url.Action("getChat", "Chat")',
success: function (data) {
alert(data);
$("#data").html(data);
},
error:{
}
});
In the controller code, I have a database query which returns multiple rows.
I want to return that variable back to JSON and print each row separately in AJAX and write that data in HTML.
Here is my Controller code
public ActionResult getChat()
{
var p = (from v in DB.chats where v.chatuserID == id select new { v.status, v.message }).ToList();
return Content(p.ToString());
}
The query is returning data. I am attaching an image that shows the variables content.
public JsonResult getChat()
{
var p = (from v in DB.chats
where v.chatuserID == id select new { v.status,
v.message
}).ToList();
return json(p,JsonRequestBehavior.AllowGet);
}
Now you can loop through the list in you ajax success callback function : here is stuff.
$.ajax({
type: "GET",
url: '#Url.Action("getChat", "Chat")',
success: function (data) {
$.each(data,function(){
console.log("Status "+ data.status +" "+"Message"+ data.message);
});
},
error:{
}
});

How can I call controller post action from jquery (in custom view page) in mvc .net web app

I am creating a web application for event management using .net mvc and jquery.
I created a mvc web app.contoller named SeatPlansController and model named SeatPlanes and I am able to insert the data to database.
But I am not able pass the data from jquery to database using the mvc controller.
My controller action code is as shown below
// GET: SeatPlans/Create
public ActionResult Create()
{
return View();
}
// POST: SeatPlans/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(String seat_id, String seat_no)
{
int id = 10;
SeatPlans S = new SeatPlans();
S.seat_id = seat_id;
S.seat_no = seat_no;
if (ModelState.IsValid)
{
db.SEATPLAN.Add(S);
db.SaveChanges();
// return RedirectToAction("Index");
}
return View(S);
}
In post create controller Id is primary key, so I want to pass seat_id,seat_no as argument and it should update the database.
I used following javascript
function getPerson(id) {
$.ajax({
type: "GET",
url: '#Url.Action("create", "SeatPlanesController")',
contentType: "application/json; charset=utf-8",
data: {eat_id :6, seat_no:8},
dataType: "json",
success: function (result) {
alert(result);
//window.locationre = result.url;
}
});
}
I am able to run the create get method using
http://localhost:52348/SeatPlans/Create
but how can I run post method directly from browser with argument
something like
http://localhost:52348/SeatPlans/Create/2/3t/e
I have changed the script as bellow,it works for GET method but if i made TYPE:"post" it popup an alert box with alert
"localhost:52348 says:
internal server error"
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("Create", "SeatPlans", new { Area = "" })',
data: { seat_id: "34", seat_no: "98" },
dataType: "json",
async: false,
success: function (result) {
$("#div1").html(result);
},
error: function (abc) {
alert(abc.statusText);
},
});
});
});
Finally i got the sollution
i changed the script as bellow
//jQuery.noConflict();
// var $j = jQuery.noConflict();
function clickevent()
{
var form = $("#frm");
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
type: "post",
// headers: { "__RequestVerificationToken": token },
url: '#Url.Action("Create", "SeatPlans")',
data: {
seat_id: "34", seat_no: "98"
},
success: function (result) {
$("#div1").html(result);
}
});
}
and change the create post method as bellow
<pre>
public ActionResult Create(String seat_id, String seat_no)
{
int id = 10;
SeatPlans S = new SeatPlans();
S.seat_id = seat_id;
S.seat_no = seat_no;
if (ModelState.IsValid)
{
db.SEATPLAN.Add(S);
db.SaveChanges();
// return RedirectToAction("Index");
}
return View(S);
}

How to receive JSON as an MVC 5 action method parameter

I have been trying the whole afternoon crawling through the web trying to receive a JSON object in the action controller.
What is the correct and or easier way to go about doing it?
I have tried the following:
1:
//Post/ Roles/AddUser
[HttpPost]
public ActionResult AddUser(String model)
{
if(model != null)
{
return Json("Success");
}else
{
return Json("An Error Has occoured");
}
}
Which gave me a null value on my input.
2:
//Post/ Roles/AddUser
[HttpPost]
public ActionResult AddUser(IDictionary<string, object> model)
{
if(model != null)
{
return Json("Success");
}else
{
return Json("An Error Has occoured");
}
}
which gives me a 500 error on the jquery side which is trying to post to it? (meaning that it didn't bind correctly).
here is my jQuery code:
<script>
function submitForm() {
var usersRoles = new Array;
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
console.log(usersRoles);
jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(usersRoles),
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
All I want to do is receive my JSON object in my mvc action?
Unfortunately, Dictionary has problems with Model Binding in MVC. Read the full story here. Instead, create a custom model binder to get the Dictionary as a parameter for the controller action.
To solve your requirement, here is the working solution -
First create your ViewModels in following way. PersonModel can have list of RoleModels.
public class PersonModel
{
public List<RoleModel> Roles { get; set; }
public string Name { get; set; }
}
public class RoleModel
{
public string RoleName { get; set;}
public string Description { get; set;}
}
Then have a index action which will be serving basic index view -
public ActionResult Index()
{
return View();
}
Index view will be having following JQuery AJAX POST operation -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$('#click1').click(function (e) {
var jsonObject = {
"Name" : "Rami",
"Roles": [{ "RoleName": "Admin", "Description" : "Admin Role"}, { "RoleName": "User", "Description" : "User Role"}]
};
$.ajax({
url: "#Url.Action("AddUser")",
type: "POST",
data: JSON.stringify(jsonObject),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(response);
}
});
});
});
</script>
<input type="button" value="click1" id="click1" />
Index action posts to AddUser action -
[HttpPost]
public ActionResult AddUser(PersonModel model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
}
So now when the post happens you can get all the posted data in the model parameter of action.
Update:
For asp.net core, to get JSON data as your action parameter you should add the [FromBody] attribute before your param name in your controller action. Note: if you're using ASP.NET Core 2.1, you can also use the [ApiController] attribute to automatically infer the [FromBody] binding source for your complex action method parameters. (Doc)
There are a couple issues here. First, you need to make sure to bind your JSON object back to the model in the controller. This is done by changing
data: JSON.stringify(usersRoles),
to
data: { model: JSON.stringify(usersRoles) },
Secondly, you aren't binding types correctly with your jquery call. If you remove
contentType: "application/json; charset=utf-8",
it will inherently bind back to a string.
All together, use the first ActionResult method and the following jquery ajax call:
jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
dataType: "json",
data: { model: JSON.stringify(usersRoles) },
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
You are sending a array of string
var usersRoles = [];
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
So change model type accordingly
public ActionResult AddUser(List<string> model)
{
}
fwiw, this didn't work for me until I had this in the ajax call:
contentType: "application/json; charset=utf-8",
using Asp.Net MVC 4.

Resources