I have a problem l need to create a comment reply action for my blog.
public JsonResult ReplyComment(string replycomment, int articleid, int commentid)
{
var UserId = Session["UserId"];
if (replycomment == null)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
db.ReplyComments.Add(new ReplyComment
{ UserId = Convert.ToInt32(UserId), ArticleId=articleid, CommentId=commentid, Date = DateTime.Now, Paragraph = replycomment });
db.SaveChanges();
return Json(false,JsonRequestBehavior.AllowGet);
}
and here is my ajax code but l have a problem here l cant reach commentid from Model and l need this variable for reply system
<script type="text/javascript">
$(document).ready(function () {
$("#reply").click(function () {
var usercomment = $("#replycomment").val();
$.ajax({
url: '/Home/ReplyComment/',
data: { replycomment: usercomment, articleid:#Model.ArticleId, commentid:},
type: 'POST',
dataType: 'json',
success: function (data) {
//alert("yorum gönderildi" + usercomment);
}
});
});
})
my article detail action
public ActionResult ArticleDetail(int id)
{
var articles = db.Articles.Where(x => x.ArticleId == id).SingleOrDefault();
if (articles == null)
{
return HttpNotFound();
}
return View(articles);
}
so l need to send 2 model to ajax.data
I think you want to pass the comment ID from AJAX to code behind, but you didnt find the way how to get comment ID. If I understood correctly, then, As this is for reply to comment, whenever you are displaying the comment, you can have the comment id in the div or span whatever you are using to build the DOM. So that, when you click the #reply, you can get the comment id and pass it to code behind.
Related
I have an input box to search ...
Html :
<form id="searchForm" asp-controller="Product" asp-action="SearchProduct" method="get">
This input performs search in two ways:
1- After pressing the Enter key
2- After the click on the "a" tag
In the first step, the address is displayed in the image below :
In the second step, the address is displayed in the image below :
After searching again, the address is displayed in the image below
JavaScript :
$('.txt-search-story').click(function () {
var span = $(this).find('span');
var txtspan = span.text();
$.ajax({
url: "/Product/GetTextSearch",
type: 'Get',
data: { "q": txtspan },
success: function (response) {
window.location.href = response.redirectToUrl;
}
});
});
Controller one :
[Route("/search/{**q}")]
public async Task<IActionResult> SearchProduct(string q, int page = 1)
{
if (q != null)
{
var searchProduct = await _product.SearchProduct(q, skip, countproduct);
ViewBag.searchtext = q;
return View(searchProduct);
}
}
Controller two for Ajax:
public IActionResult GetTextSearch(string q)
{
return Json(new { redirectToUrl = Url.Action("SearchProduct", "Product", new { q = q }) });
}
I want the second address to be like the first address What should I do?
thanks #daremachine -
I changed [Route("/search/{**q}")]
to
[Route("/search")]
it's worked
I'm getting an error that my Action Method was not found, but can't figure out what's wrong. I searched the internet now for hours but haven't found a solution till now.
In my View I have a JavaScript function:
<script type="text/javascript">
function ShowHideAds(button) {
var dAds = document.getElementById("dAds");
if (dAds.style.display == "none") {
dAds.style.display = "block"
var txtBox = "Visible";
$.post('#Html.Action("GetState","Rights")', { txtAds: txtBox });
}
else {
dAds.style.display = "none"
var txtBox = "Hidden";
$.post('#Html.Action("GetState", "Rights")', { txtAds: txtBox });
}
} </script>
I'm switching between a Textbox and a Listbox and depending on which is visible, I want to pass the parameter to my method.
My method in my Controller is the following:
[HttpPost, ActionName("GetState")]
public ActionResult GetState(string txtAds, string txtRg)
{
if (txtAds != null)
stateTxtAds = txtAds;
if (txtRg != null)
stateTxtRg = txtRg;
return View();
}
and finally here is my routing:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Before using the #Html.Action() method I had following line of code:
$.post("/Rights/GetState", { txtAds: txtBox });
but this did not work when the project was deployed so I tried to use the #Html.Action two send my variables to my controller method.
Can anyone help please?
Thank you!
GetState(string txtAds, string txtRg) has two parameters but you are only providing one. If you want it to accept two but only provide it one like you are doing in the call, do the following.
For example for the post #Html.Action("GetState", "Rights")', { txtAds: txtBox }:
GetState(string txtAds, string txtRg = "")
This way you can just send txtAds if you want and it should reach it.
The ajax I would recommend:
var json = '{txtAds: "' + txtAds + '"}'
$.ajax({
url:'#Url.Action("GetState", "Rights")',
type:'POST',
data: json,
contentType: 'Application/json',
success: function(result){
// Whatever you want to do next.
}
})
I am working on a project in Visual studio using MVC. I am trying to reload a div after a btn is clicked and data has been posted to the controller dynamically. I use an Ajax post and return a JSONresult. The code for posting looks like this:
<div id = "DelUser">
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "Dform" }))
{
<label> Select User(s) to Delete: </label>
#Html.ListBox("Users", ViewBag.Users as MultiSelectList,
new { #class = "chzn-select", #style = "width:250px; height:350 px" })
}
<button class="btn btn-primary dropdown-toggle" id="Button1" type="button" onclick="DeleteUsers()"> Delete Selected </button>
</div>
<script>
function DeleteUsers() {
var myList = []
$("#Users > option:selected").each(function () {
myList.push($(this).val());
});
jQuery.ajax({
type: 'post',
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: 'DeleteU',
data: JSON.stringify(myList),
success: function (data) {
$('#msgbx2').html(data.msg);
//here I am trying to refresh the div after the post but it fires every second
$('#DelUser').html('/Home/DeleteUser');
},
failure: function (errMsg) {
$('#msgbx2').html(data.msg);
}
});
return false;
}
The name of the controller is DeleteUser and the JSONresult controller is DeleteU.
I am trying to do this so that the dropdownlist updates after I delete the selected users. If there is another way to dynamically update this div, any information on that would be good to know too. Thank you in advance.
Here are the Controllers as well:
[HttpGet]
public ActionResult DeleteUser()
{
List<string> u = new List<string>();
object[] users = data.getDataFrmDB("Select username From `users`;");
if (users != null)
{
foreach (object[] user in users)
{
u.Add((string)user[0]);
}
}
ViewBag.Users = new MultiSelectList(u, "Username");
return View();
}
[HttpPost]
public JsonResult DeleteU(List<string> Users)
{
bool good = false;
if (Users != null)
{
foreach (string user in Users)
{
string ins = "DELETE FROM `xcal-server`.`users` WHERE username='"+user+"';";
good = data.insert_update_delete_DB(ins);
List<string> u = new List<string>();
object[] users = data.getDataFrmDB("Select username From `users`;");
if (users != null)
{
foreach (object[] usera in users)
{
u.Add((string)usera[0]);
}
}
ViewBag.Users = new MultiSelectList(u, "Username");
if (good == true)
{
ViewBag.error = "You have successfully deleted user";
}
else
{
ViewBag.error = "There was an issue removing user";
}
}
return Json(new { msg = "You have Successfully deleted Users " });
}
return Json(new { msg = "the passwords entered do not match" });
}
This is just a section of my main page that has other action functions/controllers in it which is why i did not originally post the controllers
You can simply update the existing listbox by removing the currently selected items. Start by removing onclick="DeleteUsers() from the button and use Unobtrusive JavaScript. Since you do not appear to have a POST method for DeleteUser() or a submit button, you may as well also replace #using (Html.BeginForm(...)) with just <form> elements. The script will then be
$('#Button1').click(function () {
var selected = $('#Users option:selected'); // store the selected users
if (selected.length == 0) {
return; // no point making a post
}
var users = [];
$.each(selected, function (index, item) {
users.push($(this).val());
})
$.ajax({
type: 'post',
dataType: 'json',
url: '#Url.Action("DeleteU", "yourControllerName")', // always use Url.Action to generate your url's
data: { users: users },
traditional: true,
success: function () {
// remove the currently selected options
selected.remove();
}
});
})
However a lot of the code in your controller does not make sense. Your adding values to ViewBag and even creating a SelectList but your not returning a view (your returning json), so all that is lost. And even if you were returning a view, your loop keeps overwriting the value of ViewBag.error so that only the last value would be set. Ideally, you should be calling a service to delete the users by passing the user name (or a collection of user names so that they are all deleted in a transaction). But based on you current code, you controller method can be
[HttpPost]
public JsonResult DeleteU(List<string> Users)
{
if (Users == null)
{
// throw an error that can be caught in the ajax error handler
}
List<string> deletedUsers = new List<string>();
foreach (string user in Users)
{
string ins = "DELETE FROM `xcal-server`.`users` WHERE username='"+user+"';";
if (data.insert_update_delete_DB(ins))
{
deletedUsers.Add(user);
}
}
return Json(deletedUsers);
}
and then the ajax success callback
success: function (data) {
$.each(data, function(index, item) {
// remove each item that was successfully deleted in the controller
$('#Users option:contains("' + item + '")').remove();
}
}
i think you need to add a $(document).ready(function(){}); around your script
Possibly someone asked question like as my question. But, I can't find any solution.
ProfileEditor.php (controller)
method 1:
public function modify_personal_information() {
$this->data['userinfo'] = $this->personal_information_of_mine($userid);
$this->load->view('layouts/header', $this->data);
$this->load->view('profile/personalinformation', $this->data);
$this->load->view('layouts/footer', $this->data);
}
method 2:
public function check_url_if_exists() {
$newportalurl = $this->uri->segment(2);
$this->results = $this->profile_model->checknewportalurl($newportalurl);
if ($this->results == 1) {
$this->status['status'] = 1;
$this->status['msg'] = 'This name is available. Thanks.';
} else {
$this->status['status'] = 0;
$this->status['msg'] = 'This name is not available. See suggestions.';
}
$this->load->view('profile/layouts/availiability', $this->status);
//or echo json_encode($this->status);
}
profile/personalinformation.php (views)
a form with <div id="urlsuggestions"></div>
profile/layouts/availiability.php (views)
where i am printing the message which i am getting from the check_url() function
ajax.js (ajax)
$('#newportalurl').blur(function() {
var fval = $(this).val();
var ifexists = fval.toLowerCase().replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '');
$.ajax(baseurl + "check/"+ifexists, function(data) {
//i tried following things
//alert(window.location);
//$('#msgbox').html(data.msg).show().addClass('alert-success').delay(2000).fadeOut();
//$('#urlsuggestions').load(window.location + 'modifypersonalinformation #urlsuggestions');
});
});
Now, I am trying to load the message to personalinformation view. What I am doing wrong or what will be the procedure to do it? I actually want to know the process how codeigniter handle them.
Please try like this, im not able to get response from your metod.
$.ajax({
url: "<?= base_url("check/") ?>"+ifexists,
success: function (data) {
$("#urlsuggestions").html(data);// if you want to replace the data in div, use .html()
or if you want to append the data user .append()
}
});
Hi sorry for asking such an easy question but I'm scratching my head all day today and cannot figure this out. I found lots of similar questions but non of them resolve my problem.
I had a page with list of products and few buttons to filter products by category. Because number of products has increased I decided to change them to drop down box.
So I have drop down box which populates categories:
#Html.DropDownListFor(m => m.SelectedCategoryId, Model.CategoryItems, new { id = "changeCategory" })
and javascript which fires on change event:
<script type="text/javascript">
$(document).ready(function () {
$("#changeCategory").change(function () {
var selectedCategory = $(this).text();
$.ajax({
url: '#Url.Action("List", "Deal")',
type: 'GET',
data: { category: selectedCategory },
cache: false,
});
});
});
</script>
This doesn't work. My previous routing works with the code below:
#foreach (var link in Model) {
#Html.RouteLink(link, new {
controller = "Deal",
action = "List",
category = link,
page = 1
}, new {
#class = "btn btn-block btn-default btn-lg"
})
}
UPDATE:
I have changed the jQuery code to:
<script type="text/javascript">
$(document).ready(function () {
$("#changeCategory").change(function () {
var selectedCategory = $("#changeCategory option:selected").text();
$.ajax({
url: selectedCategory,
type: 'POST',
cache: true,
});
});
});
</script>
and the link looks correct now but the website doesn't reload. When I watch this in the Chrome Developer Tool in Network section the link appear there and when I click it it does open correct page.
Why it doesn't do that on website?
UPDATE 2
My Controller
public ViewResult List(string category, int page = 1)
{
DealsListViewModel model = new DealsListViewModel
{
Deals = repository.Deals
.Where(p => category == null || p.Category == category)
.OrderBy(p => p.DealID)
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = repository.Deals.Count()
},
CurrentCategory = category
};
return View(model);
}
Any help is appriciated
It appears you want to redirect to the List method of DealController and pass the text of the selected option. If so then
$("#changeCategory").change(function () {
window.location.href = '#Url.Action("List", "Deal")' + '/' + $(this).find('option:selected').text();
});
assuming your action method is something like
public ActionResult(string someValue)
AJAX calls stay on the same page and do not redirect to another page.
And out of curiosity, why override the default id (and not just use $("#SelectedCategoryId").change(...)?
Edit
If you want to return some html to include on the page, return a partial view and update the page html in the AJAX success function
Controller
public PartialViewResult List(string category, int page = 1)
{
DealsListViewModel model = new DealsListViewModel ....
....
return PartialView(model)
}
Script (assumes you have an element with `id="results" where you want to render the returned html)
$("#changeCategory").change(function () {
var url = '#Url.Action("List", "Deal")';
var category = $(this).find('option:selected').text();
var page = ? // if you want to pass this as well
$.get(url, { category: category, page: page }, function(data) {
$('#results').html(data);
});
});
Try the following in your ajax call:
type: 'POST'