How to pass data to ajax function with json? - c#

I need to get an id from the URL , comment value from textbox, save it to database and show on page with ajax.
Im not sure how should look correct syntax in my controller and ajax function.
Controller
[HttpPost]
public JsonResult AddComment(int id, string comment)
{
if (ModelState.IsValid)
{
return Json(true); // what should be here
}
return Json(true);
}
Ajax
$('#submit').click(function () {
$.ajax({
url: '/Form/AddComment',
method: 'POST',
data: {
id: 4, //how to get id from url?
comment: 'test' //how to get textbox value?
},
success: function (data) {
console.log(data)
},
error: function (a, b, c) {
console.log('err')
}
})
});
this just show me that it work but i dont know how to move forward

Based upon your requirement, you would have to do the appropriate form handling at client side in order to get your variables like id and comment. You can use strongly typed model binding to get your form values and process them on submit or you can use JavaScript techniques to process your form variables. To extract out id from a URL, you can use a Regular Expression or other JavaScript string parsing techniques. I am giving you a simple example of getting your id from a URL and comment from a text box using JavaScript:
Your input control would look like:
<input type="text" id="commentBox" name="Comment" class="form-control" />
In order to achieve your desired functionality using AJAX to POST your form variables to controller, refer to the following code snippet:
AJAX:
<script type="text/javascript">
var url = 'http://www.example.com/4'; //Example URL string
var yourid = url.substring(url.lastIndexOf('/') + 1);
var yourcomment= document.getElementById('commentBox').value;
var json = {
id: yourid, //4
comment: yourcomment
};
$('#submit').click(function (){
$.ajax({
url: '#Url.Action("AddComment", "Form")',
type: "POST",
dataType: "json",
data: { "json": JSON.stringify(json)},
success: function (data) {
console.log(data)
},
error: function (data) {
console.log('err')
},
});
};
</script>
And you can get your values in your Controller like this:
using System.Web.Script.Serialization;
[HttpPost]
public JsonResult AddComment(string json)
{
if (ModelState.IsValid)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
string id= jsondata["id"];
string comment=jsondata["comment"];
// Do something here with your variables.
}
return Json(true);
}

My solution looks like this:
controller:
[HttpPost]
public JsonResult AddComment(int id_usr,string comment)
{
if (ModelState.IsValid)
{
Comments kom = new Comments();
kom.DateComment = DateTime.Now;
kom.Id_usr = id_usr;
kom.Comment = comment;
db.Comments.Add(kom);
db.SaveChanges();
return Json(kom);
}
return Json(null);
}
View
var url = window.location.pathname;
var idurl = url.substring(url.lastIndexOf('/') + 1);
$('#submit').click(function () {
console.log('click')
$.ajax({
url: '/form/AddComment',
method: 'POST',
data: {
comment: $("#Comments_Comment").val(),
id_usr: idurl,
},
success: function (data) {
console.log(data),
thank you all for guiding me to the solution

Related

Ajax Posting twice ASP NET CORE MVC

Controller
[HttpPost]
public IActionResult Index(string mainFin, string actNumber, int actTypeId)
{
int userId = Int16.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier));
Act act = new Act()
{
ActTypeId = actTypeId,
CreateDate = DateTime.Now,
ApproveDate = null,
UserId = userId,
StatusId = 1,
};
_unitOfWork.ActRepository.Add(act);
_notyf.Success("Arayış əlavə edilid !");
_unitOfWork.Complete();
return RedirectToAction("Marriage");
}
AJAX
$(function () {
var actTypeId = $("#questList option:selected").val();
console.log("QuestList ishledi !");
$('#formSubmit').click(function (e) {
var mainFin = $("#FinInput").val();
var actNumber = $("#actNumber").val();
console.log(mainFin);
$.ajax({
url: "/Home/Index",
type: "POST",
data: { mainFin: mainFin, actNumber: actNumber },
success: function (data) {
console.log("+++++");
},
error: function () {
console.log("------");
}
});
e.preventDefault();
$("#questForm1").submit();
});
});
Problem : When I click submit button data inserts twice to database (AJAX makes 2 request at same time )
If you want to submit the form via AJAX then you need to remove the last line of the click event handler.
$("#questForm1").submit();
This line is submitting the form and essentially negating the e.preventDefault() above.
You are submitting your data twice: at first using ajax and after that using using the form submit.
You have to remove one of them, I would guess the form submit.
Also, since ajax is called async, if you want to do something after ajax has been called and returned successfully, you have to put the code in success section.
So the code should look like:
$(function () {
var actTypeId = $("#questList option:selected").val();
console.log("QuestList ishledi !");
$('#formSubmit').click(function (e) {
e.preventDefault();
var mainFin = $("#FinInput").val();
var actNumber = $("#actNumber").val();
console.log(mainFin);
$.ajax({
url: "/Home/Index",
type: "POST",
data: { mainFin: mainFin, actNumber: actNumber },
success: function (data) {
console.log("+++++");
// do your thing here, once the ajax requst has returned successfully
},
error: function () {
console.log("------");
}
});
// NOTICE: form submit removed
});
});

Asp.net pass jQuery variable to C# function

I have go this code inside my razor view in Asp.Net:
#section MyScripts {
<script type="text/javascript">
$("button").click(function () {
var myVariable = this.id;
#{
var Line1 = "Software";
var Gruppe2 = Model.Where(x => x.Line1 == "Software").GroupBy(v => v.Line2).ToList();
}
});
</script>
}
As you can see, the myVariable receives the id via jQuery from the "button click event".
So lets say that the variable value is "Software".
How can I pass this variable to the c# code inside the jQuery?
Add an Ajax call to your click event that does a POST/GET back to your MVC action, something like this:
$.ajax({
async: false,
cache: false,
url: '#Url.Action("MyAction", "MyController")',
type: 'GET',
dataType: 'json',
data: myJsonString }
);
Your action would only return json (or a partial view, depending on the return type)
[HttpGet]
public JsonResult MyAction()
{
string result = [some model data]
var json = Json(result, JsonRequestBehavior.AllowGet);
return json;
}

Redirect in .Net Core Application

im trying to do some operation .Net Core and after this operation is done, i want to redirect it to a .cshtml page. In homepage i have table, after selecting a row in the table, im sending the value of the cell with ajax.
AJAX
$('#table').find('tr').click(function () {
var userName = $(this).find('td').text();
$.ajax({
url: "/Profile/printUser",
type: 'POST',
data: { "DisplayName": userName }
});
});
After this part, im going to this area
FUNCTION
[HttpPost]
public IActionResult printUser(User user)
{
user.DisplayName = user.DisplayName.Replace("\n", String.Empty);
user.DisplayName = user.DisplayName.Trim(' ');
User findUser = UserAdapter.GetUserByUserName(user.DisplayName);
return RedirectToAction("ProfileScreen",findUser);
}
My operations are finished, i found my user. All i want to do is print this users information in cshtml. But i cant send myselft to the page. How can i redirect myself? Thanks.
INDEX
public IActionResult ProfileScreen()
{
return View();
}
You can't redirect from Ajax call in the backend. Use AJAX's
success: function(){
windows.location.href = '/ProfileScreen';
}
If you want to pass data back, return JSON from MVC action and your JavaScript would be:
$('#table').find('tr').click(function () {
var userName = $(this).find('td').text();
$.ajax({
url: "/Profile/printUser",
type: 'POST',
data: { "DisplayName": userName },
success: function(data){
window.location.href = '/ProfileScreen' + data.ID; //or whatever
}
});
});
SOLUTION
FUNCTION
[HttpPost]
public JsonResult printUser(User user)
{
user.DisplayName = user.DisplayName.Replace("\n", String.Empty);
user.DisplayName = user.DisplayName.Trim(' ');
User findUser = UserAdapter.GetUserByUserName(user.DisplayName);
return Json(new { displayName = findUser.DisplayName});
}

MVC Droplist to trigger controller to get data to populate another droplist

We were able to do this with Angular, but are trying to do this with MVC using C# and Razor and possibly jQuery if need be.
What we are trying to do is, we populate a dropdown list with data already populated. (done). In our View we put an onChange event in which we then want to trigger another method in the controller so that we may get another list of items to populate the next droplist.
IN doing some VERY simple examples,we keep either getting a 404 or 500 return in our browser console and not hitting any breakpoints in Visual Studio.
This is what I have so far:
View
<div> #Html.DropDownListFor(model => model.Name, Model.AvailableGalaxyEventTypes, new { #id = "eventTypeName", onchange = "GetEventNames();" })
</div>
<script>
function GetEventNames() {
var url = '#Url.Action("GetData")';
var strId = 0;
$.ajax({
url: url,
type: 'GET',
cache: false,
data: { value: strId },
success: function (result) {
alert(result);
console.log(result);
$('#result').html(result);
}
});
}
</script>
Controller
public ActionResult GetData(string id)
{
return Json(new { foo = "bar", ball = "dragon" });
}
I don't understand why we are not getting a success or anything back doing this very simple example. I should get Foo and Ball back. If we could get to the controller method, we should be able to make headway but I am getting 404 or 500 now.
Any ideas?
your method is accepting parameter id but you are passing value as parameter in ajax request
data: { id: strId }
or try by specifying controller name as well as action method name explicitly
url: '#Url.Action("Foo", "SomeController")',
#Html.DropDownListFor(model => model.CountryId, Model.AvailableCountries)
#Html.DropDownListFor(model => model.RegionId, Model.AvailableRegions)
$("##Html.FieldIdFor(model => model.CountryId)").change(function () {
var selectedItem = $(this).val();
var ddlRegions = $("##Html.FieldIdFor(model => model.RegionId)");
$.ajax({
cache: false,
type: "GET",
url: "#(Url.RouteUrl("GetRegionsByCountryId"))",
data: { "countryId": selectedItem, "addSelectStateItem": "true" },
success: function (data) {
ddlRegions.html('');
$.each(data, function (id, option) {
ddlRegions.append($('<option></option>').val(option.id).html(option.name));
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve regions.');
}
});
And extension method that gets Id of DDL (or you can do it using JQuery or Vanilla JS):
public static string FieldIdFor<T, TResult>(this HtmlHelper<T> html, Expression<Func<T, TResult>> expression)
{
var id = html.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
// because "[" and "]" aren't replaced with "_" in GetFullHtmlFieldId
return id.Replace('[', '_').Replace(']', '_');
}
And method in controller:
public ActionResult GetRegionsByCountryId(string countryId)
{
var country = _countryService.GetCountryById(Convert.ToInt32(countryId));
var states = _stateProvinceService.GetStateProvinces(country != null ? country.Id : 0).ToList();
var result = (from s in states
select new {id = s.Id, name = s.Title})
.ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}

Searching in asp.net mvc4

I am newbie to asp.net MVC4.
For searching names from list i tried a search filter in MVC4.
This is controller-
public ActionResult SearchUser(string Email, int? UserId) {
var system = from u in db.SystemUsers
select u;
if (!String.IsNullOrEmpty(Email)) {
system = system.Where(c => c.Email.Contains(Email));
}
return View(system.Where(x=>x.Email==Email));
}
View-
<input type="text" id="search-User" />
<button id="text-email">search</button>
Ajax handling-
<script type="text/javascript">
$(document).ready(function () {
$('#text-email').click(function () {
var areavalue = $('#search-User').val();
alert(areavalue);
$.ajax({
url: '/Allusers/SearchUser/?Email=' + areavalue,
type: 'get',
datatype: 'json'
});
});
});
</script>
ViewModel-
public class UserModel
{
[Required]
public string Email { get; set; }
public int UserId { get; set; }
}
I have many users as a list, so i wanted to filter out any user from the list. For this I am using input element to get exact name as it is in list. Thus this name is passed to controller to find the exact match.
It is showing value i passed through ajax handling but not showing filtered result.
How can I perform searching in Asp.net MVC4?
I would use better Load() function for this porpose:
<script>
$(function () {
$('#text-email').click(function () {
var areavalue = $('#search-User').val();
$(".YourDivForResults").Load('/Allusers/SearchUser/?Email=' + areavalue)
});
});
</script>
And, as a recommendation, modify a bit your ActionResult as follows:
system = system.Where(c => c.Email.ToUpper().Trim().Contains(Email.ToUpper().Trim()));
This way you will avoid problems with empty spaces and Upper or Low letters.
Your ajax function is sending the data up to the server, but it is not doing anything with the result. In order to use the results, you should use the done promise method in the jQuery .ajax method that you are calling. It will look something like this:
$.ajax({
url: '/Allusers/SearchUser/?Email=' + areavalue,
type: 'get',
datatype: 'json'
}).done(
function(data, textStatus, jqXHR) {
var object = jQuery.parseJSON(data);
// LOGIC FOR UPDATING UI WITH RESULTS GOES HERE
}
);
You could alternatively use the Success callback option (instead of done). But the key is to provide logic for what to do with the data returned by the Action.
Also, if you are intending to return results using your ViewModel, you may need to return UserModel objects from your Linq query.
And if you are expecting JSON back from your action, you should not return View. Instead, try returnins JSON(data). (See here for more).
You need to make small change to you action like,
public ActionResult SearchUser(string Email, int? UserId) {
var system = from u in db.SystemUsers
select u;
if (!String.IsNullOrEmpty(Email)) {
system = system.Where(c => c.Email.Contains(Email));
}
return Json(system.Where(x=>x.Email==Email),JsonRequestBehavior.AllowGet);
}
and in your ajax call
$(document).ready(function () {
$('#text-email').click(function () {
var areavalue = $('#search-User').val();
alert(areavalue);
$.ajax({
url: '/Allusers/SearchUser/?Email=' + areavalue,
type: 'get',
datatype: 'json',
success:function(data){JSON.stringify(data);}
});
});
});
so that you will get the search result in a json format. you can make use of it. Hope it helps

Categories

Resources