I'm listing a list of clients in a partial view
#{
List<Clients> clientsList = ViewBag.ClientsList;
}
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<li class="dropdown">
Clients <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
#foreach (Clients c in clientsList)
{
<li>#Html.ActionLink(c.NomClient, "Index", "Home", new {c.ID}, null)</li>
}
</ul>
</li>
What I want is, when a user click on a client in the dropdown list, it send the client to ID to a method on a controller, without clicking on a submit button, with or form for example.
I tried with an ActionLink, but only by passing the id in the URL and I would like to not have the clientId in the URL.
How can I do that ?
thx
Do as
HTML:
<ul class="dropdown-menu" role="menu">
#foreach (Clients c in clientsList)
{
<li>#c.NomClient</li>
}
</ul>
javascript:
// assuming you're using jQuery
$(".dropdown-menu").change( function (event) {
$.ajax({
url: "Home/Index/" + $(this).val(),
data: { id = $(this).val() /* add other additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
//do stuff
}
});
});
You can use Jquery for that.
Create a class on your li and an event on click on this class. Simply redirect your page with a window.location.href and a #Url.Action().
JQuery
$(".dropdownclient").click(function(){
window.location.href="#Url.Action('Method','Controller')/"+$(this).data("id");
});
HTML
<ul class="dropdown-menu" role="menu">
#foreach (Clients c in clientsList)
{
<li class='dropdownclient' data-id="#c.ClientID">#Html.ActionLink(c.NomClient, "Index", "Home", new {c.ID}, null)</li>
}
</ul>
Try this with jQuery. Your ID will not be part of the URL.
<ul class="dropdown-menu" role="menu">
#foreach (Clients c in clientsList)
{
<li><button data-action="do-stuff" data-url="#Url.Action("Index", "Home")" data-id="#c.ID">#c.NomClient</button></li>
}
</ul>
$("[data-action='do-stuff']").on('click', function (event) {
var opt = $(this).data();
$.ajax({
url: opt.url,
data: { id = opt.id },
cache: false,
type: "POST"
success: function (data, textStatus, XMLHttpRequest) {
//do stuff
}
});
});
#Html.DropDownListFor(m => m.NomClient, new SelectList(ViewBag.ClientsList,"Key", "Value"), "Select", new { #class = "dropdown-menu" })
$(".dropdown-menu").change(function (event) {
$.ajax({
url: "Home/Index/",
data: { id = $(this).val() /* add other additional parameters */ },
type: "POST",
success: function (data) {
//do stuff
}
});
});
Related
I have a form in which I am posting data using ajax using jquery. Problem is, when I alert #Model.Id or when I try to pass the value in FormData in the view, I can't see the alert and when I keep the breakpoint in the Controller, I get the breakpoint fine upon clicking the Post Comment button. I also get all values on the form except for the Id Please help.
(And please see the document ready function, there I can access the Id fine. Only when I click the Post Comment button, I have the problem with the Id.)
Here is my View
#model KGSBlog.Models.BlogData
#{
Layout = null;
}
<html>
<body>
<form id="formPostComment" method="post" asp-controller="BlogData" asp-action="PostComment">
<div class="row">
<div class="col-md-6">
<input type="text" placeholder="Name *" name="name" required>
</div>
<div class="col-md-6">
<input type="email" placeholder="Email *" name="email" required>
</div>
</div>
<textarea name="message" placeholder="Message *" id="message" cols="45" rows="10" required></textarea>
<button type="submit" id="btnPostComment" class="btn btn-main m-bottom-40">Post Comment</button>
</form>
<!-- jQuery -->
<script src="~/js/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="~/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
LoadPartialView(#Model.Id); //Here I can access the Id fine.
$('#formPostComment').validate({
rules: {
name: {
required: true,
minlength: 4
},
email: {
required: true,
email: true
},
message: {
required: true,
minlength: 10
}
}
});
});
$(function () {
$("#btnPostComment").click(function () {
alert(#Model.Id); // I cannot see this alert.
var url = $("#formPostComment").attr("action");
var formData = new FormData();
formData.append("Name", $("#name").val());
formData.append("Email", $("#email").val());
formData.append("Comment", $("#message").val());
formData.append("BlogId", #Model.Id); //This value is always 0.
$.ajax({
type: 'POST',
url: url,
data: formData,
processData: false,
contentType: false,
success: function (response) {
LoadPartialView(response.blogId);
$('#formPostComment')[0].reset();
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
function LoadPartialView(blogId) {
$.ajax({
type: 'POST',
url: "/BlogData/UpdateCommentsPartial",
data: { "blogId": blogId },
success: function (data) {
$("#haveToReloaddiv").html(data);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
})
}
</script>
</body>
</html>
When I hit the Post Comment button I see the break point in the Controller action method with all the values of the form, but the Id is always 0.
AJAX function is not passing Id parameter to GET method in my controller.
I have this table.
#foreach (var user in Model)
{
<tr>
<td>#user.FirstName</td>
<td>#user.LastName</td>
<td>#user.Email</td>
<td>#string.Join(" , ", user.Roles.ToList())</td>
<td>
<a class="btn btn-primary" onclick="manageRolePopup('#Url.Action("Manage","Role", new {id=user.UserId },Context.Request.Scheme)')">Manage Roles</a>
<partial name="_RoleManagePopup.cshtml" />
</td>
</tr>
}
On click I want to show in popup user first name and last name so I have this in my Controller
[HttpGet]
public async Task<IActionResult> Manage(string userId)
{
var user = await _userManager.FindByIdAsync(userId);
ViewBag.FirstName = user.FirstName;
ViewBag.LastName = user.LastName;
var model = new ManageRoleViewModel();
List<string> roleNames = new List<string>();
foreach(var role in _roleManager.Roles)
{
model.RoleId = role.Id;
roleNames.Add(role.Name);
}
model.UserId = user.Id;
model.RoleNames = roleNames;
return View(model);
}
AJAX
manageRolePopup = (url) => {
$.ajax({
type: "GET",
url: url,
success: function (res) {
$("#form-modal .modal-body").html(res);
$("#form-modal").modal("show");
}
})
}
View
<form method="post" asp-controller="Role" asp-action="Manage" asp-route-UserId="#Model.UserId">
<div class="row">
<div class="col-3">
<h4>#ViewBag.FirstName #ViewBag.LastName</h4>
<div class="form-group">
<select asp-items="#new SelectList(Model.RoleNames)">
<option selected disabled>---Select New Role---</option>
</select>
</div>
</div>
</div>
</form>
When im passing Id like below, everything is good. User is not null, Id parameter also.
<a asp-controller="Role" asp-action="Manage" asp-route-UserId="user.UserId"></a>
Obviously I want to do UPDATE method but for now I just want to have it displayed.
you have to add userId to your ajax url
manageRolePopup = (userId) => {
var url = #Url.Action("Manage","Role");
$.ajax({
type: "GET",
url: url+"?UserId="+userId,
....
Since you have a list of UserIds you need or add UserId data attribute to you ancore tag, or push it as input parameter
<a class="btn btn-primary" onclick="manageRolePopup(#user.UserId)>Manage Roles</a>
but it is better to use modern javascript syntax
<script type="text/javascript">
$(document).ready(function () {
$(document).on("click", ".userBtn", (function (e) {
e.preventDefault();
e.stopImmediatePropagation();
var userId= this.id;
var url = #Url.Action("Manage","Role");
$.ajax({
type: "GET",
url: url+"?UserId="+userId,
....
}));
});
</script>
and view
<a id="#user.UserId" class="userBtn btn btn-primary"> Manage Roles </a>
I've a parent view which contains a table of data. This View contains two modal dialog as shown in below code:-
<div id='myModal' class='modal fade in' data-keyboard="false" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content" style="width: 400px; height:250px;">
<div id='firstModelContent'></div>
</div>
</div>
</div>
<div class="modal fade" tabindex="-1" id="callBackModal" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content" style="width: auto;">
<div id='secondModalContent'></div>
</div>
</div>
</div>
On each row click of table, firstModal dialog will popup with row data as parameter. Now the requirement is to initiate the second modal popup from the "submit button" of first modal.
I'm able to load a partial view as the firstmodal dialog with row parameters using AJAX. But I'm unable to load a partial view as secondmodal dialog on a button click of firstmodal partial view. Instead while debugging the secondmodal doesn't gets checked. It will simply redirect to partial view on a full screen page. The html link that gets auto-generated from the firstmodal dialog partial view looks like below:-
<a class="btn btn-primary" data-modal="" href="/SampleController/Update?ID=867448&status=Yes" title="Update Details">Yes</a>
And the AJAX code for second modal is like below **in the parent page JavaScript **:-
$(function () {
$("a[data-modal]").on("click", function (e) {
debugger;
var $buttonClicked = $(this);
//var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: '#Url.Action("Update", "SampleController")',
contentType: "application/json; charset=utf-8",
data: { "Id": id },
datatype: "json",
success: function (data) {
debugger;
$('#myModalContent').html(data);
$('#callBackModal').modal(options);
$('#callBackModal').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
//$("#closbtn").click(function () {
// $('#callBackModal').modal('hide');
//});
});
});
But the first modal popup on "button" click doesn't open the second modal pop.
Can anyone please suggest how to perform this operation?
Looking forward to hearing from you.
When you click the link :
<a class="btn btn-primary" data-modal="" href="/SampleController/Update?ID=867448&status=Yes" title="Update Details">Yes</a>
it will not execute your ajax call.
You must change it to "button" :
<button type="button" class="btn btn-primary btn-yes">Yes</a>
jQuery:
$(".btn-yes").on("click", function (e) {
var $buttonClicked = $(this);
//var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: '#Url.Action("Update", "SampleController")',
contentType: "application/json; charset=utf-8",
data: { "Id": id },
datatype: "json",
success: function (data) {
debugger;
$('#myModalContent').html(data);
$('#callBackModal').modal(options);
$('#callBackModal').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
this is my drop down :#Html.EditorFor(m => m.CustomerBasicInfo.CheckUpDR)
i want it to be updated either whenever it's been clicked or when a reload button hit. i mean i wonder if i can reload it even by clicking on it but if its not possible i want it to reload by hitting reload button.
for example here i put a button and it call an ajax function:
<div class="row">
<div class="col-md-11">
#Html.EditorFor(m => m.CustomerBasicInfo.CheckUpDR)
</div>
<div class="col-md-1">
<a href="#" class="btn" sdata-placement="top" onclick="ReloadDropDown()">
<i class="fa fa-plus"></i>
</a>
</div>
</div>
and here is the ajax function :
function ReloadDropDown() {
debugger;
$.ajax({
type: "GET",
url: '#Url.Action("FillCheckDrDropDown", "CustomerInfoControler")',
data: { },
success: function (res) {
$("#CheckUpDR").value(res);
alert('Successfully called');
},
error: function (jqxhr, status, exception) {
alert('Exception:', exception);
}
});
}
and here is the controller for loading data:
public JsonResult FillCheckDrDropDown()
{
var model = _service.GetCheckUpDRLists();
return Json(model, JsonRequestBehavior.AllowGet);
}
with considering that i'm very new to ajax would you pleas help me where i'm going wrong that my ajax function doesn't work and what i can do to update the drop down.thank you.
In my view I have a modal window, it have the next form...
#using (Html.BeginForm("controllerAction", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="container" id="editRecordForm">
<div class="row">
<div class="col-md-6">
#Html.LabelFor(model => model.Author)
#Html.TextBoxFor(model => model.Author, new { #class = "form-control", #style = "height:auto" })
#Html.ValidationMessageFor(model => model.Author)
</div>
</div>
<br/>
<div class="row">
<div class="col-md-6">
#Html.LabelFor(model => model.Image)
<input type="file" name="file" accept="image/*">
</div>
</div>
<br />
<input type="submit" value="Submit" class="btn btn-primary">
</div>
}
this is the JS that contains the ajax request
<script>
var formdata = new FormData($('form').get(0));
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
cache: false,
data: formdata,
success: function (status, data) {
console.log(data);
}
});
}
return false;
});
</script>
The action controller receives two parameters the model and file
[HttpPost]
public async Task<JsonResult> controllerAction(HttpPostedFileBase file, Model model)
{
var json = new
{
Success = true,
StatusCode = "200",
ErrorDesc = "OK",
ErrorCode = "",
NewId = ""
};
//some process
return Json(json, JsonRequestBehavior.AllowGet);
}
The problem is why when the controller action finish, it redirects to the action controller url
http://controller/action
and it does not stay on the same page?
What Im doing wrong?
You are not preventing the default action of the form.
$('form').submit(function (e) {
e.preventDefault();
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
cache: false,
data: formdata,
success: function (status, data) {
console.log(data);
}
});
}
return false;
});
The problem was the bad config on the javascript- ajax part
$('form').submit(function () {
var formdata = new FormData($('form').get(0));
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
cache: false,
processData: false,
contentType: false,
data: formdata,
success: function (status, data) {
console.log(data);
}
});
}
return false;
});
thanks to Stephen for the help.