I place a text box in the bootstrap modal popup and also I have a kink in the table data in the table come from database so I want when I click pop-up show database cell value in the textbox that exists in the modal-popup. Below is my code
Thats my action method that gets data and data is passing to the ViewBag.Type
public JsonResult LinkButton(int RoelID)
{
Role model = new Role();
Session["State"] = RoelID;
int id = RoelID;
RoleServices ser = new RoleServices();
var data = ser.Get(id);
bool result=false;
if(Session["State"]!=null)
{
ViewBag.Type = data.RoleType;
result=true;
}
return Json(result, JsonRequestBehavior.AllowGet);
}
Here is a code of JQuery and Ajax acall the action method on link click
Select
<script>
var UpdateID = function (RoelID) {
$("#hiddenID").val(RoelID);
var roleID=$("#hiddenID").val();
$.ajax({
type: "post",
url: '#Url.Action("LinkButton", "Account")',
data: { RoelID: roleID },
success:function()
{
$("moReg").modal('hide');
}
})
$("#moReg").modal('show');
}
</script>
Here is textBox in the Modal PopUp
#Html.TextBoxFor(model => model.RoleType, new { #value=ViewBag.Type })
You can return your data like bellow,
return this.Json(new { result = true, Type = data.RoleType },
JsonRequestBehavior.AllowGet);
Then in your ajax success method, you can retrieve the value like,
success:function(data)
{
var _result = data.result;
var _Type = data.Type ;
}
Related
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
I am trying to get the value of an item in a dropdownlist and pass it to the controller using an ajax post, but whatever I pass keeps returning as null.
DropDownList:
<div class="form-inline">
#Html.DropDownList("People", null, new { #id = "personID", #class = "form-control" })
<button onClick="setTimeout( initCalendar, 5000 );" type="button" id="btnInit" data-backdrop="static" data-keyboard="false" data-toggle="modal" href="#loadingModal" class="btn btn-info">Initialise Calendar</button>
</div>
ajax post:
function initCalendar() {
// This function will be executed when you click the element
// show the element you want to show
$("#loadingModal").show();
alert($('#personID').val(""));
//var dataRow = {
// 'ID': $('#personID').val()
//};
var dataRow = $('#personID').val();
console.log(dataRow);
console.log($('#personID').length);
$.ajax({
type: 'POST',
url: "/Event/SelectPerson",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(dataRow)
});
startCalendar();
// Set a timeout to hide the element again
setTimeout(function () {
$('#loadingModal').modal('hide');
}, 5000);
}
Controller:
public ActionResult Index()
{
ViewBag.Hours = GetHoursList();
ViewBag.People = GetPeopleList();
return View();
}
// Finds all people in the database and adds them to a list for a dropdownlist.
public List<SelectListItem> GetPeopleList()
{
List<SelectListItem> peopleList = new List<SelectListItem>();
var people = from s in db.People
select s;
foreach (Person person in people)
{
peopleList.Add(new SelectListItem
{
Text = person.Forename + " " + person.Surname,
Value = person.ID.ToString()
});
}
//var sortedPeopleList = (from person in peopleList
// orderby person.Text
// select person).ToList();
return peopleList;
}
public void SelectPerson(int ID)
{
Person person = db.People.Where(p => p.ID == ID).FirstOrDefault();
Session["Person"] = person;
}
When I log the JSON, the ID is always null and I cant figure out why.
Thanks in advance.
The following line
alert($('#personID').val(""));
is setting the value of the element with id="personID" to null. You need to change it to
alert($('#personID').val());
try this one.
var dataRow = $('#personID').val();
I have an issue with a dropdownlist and I can't figure it out how to solve it.
There are two different way to get into my view: Add New and Edit.
1) Add New: In this situation my dropdownlist is related to another one, and everything works great.
the dropdownlist is locked and empty until I select something in the other one.
2) Edit: In this situation my dropdownlist is already binded using stored data. Of course if I change the selected item in the "parent" one I want to change data to the children too.
The problem appears in the 2 case: When I select something else out of the stored data in the related dropdownlist.
It binds the correct data, but it gives an empty item as first, and not the first of the data.
How can I solve it?
<%=Html.Kendo().DropDownListFor(model => model.GNR_FK)
.Name("GNR_FK") .BindTo((IEnumerable<Models.Widget.Combo>)ViewData["Customer"])
.DataTextField("descriptionText")
.DataValueField("valueID")
.Value(Model.GNR_FK.ToString())
.Events(e =>
{
e.Select("onSelect");
})
%>
<%=Html.Kendo().DropDownListFor(model => model.CNT_FK) .BindTo((IEnumerable<Models.Widget.Combo>)ViewData["Sender"])
.Name("CNT_FK")
.DataTextField("descriptionText")
.DataValueField("valueID")
%>
Condition:
if (Model.PK == 0)
{
loadValues(current);
}
else
{
loadEditValues(current);
}
public JsonResult loadValues(Models.Model current, int PK = 0)
{
IDataReader sender = Model.getSender(PK);
Models.Widget.Combo SenderNA = new Models.Widget.Combo();
List<Models.Widget.Combo> receiveSender = new List<Models.Widget.Combo>();
SenderNA.valueID = 0;
SenderNA.descriptionText = "NA";
receiveSender.Add(SenderNA);
while (sender.Read())
{
Models.Widget.Combo newItem = new Models.Widget.Combo();
newItem.valueID = int.Parse(sender["PK"].ToString());
newItem.descriptionText = sender["SURNAME"].ToString();
receiveSender.Add(newListItem);
}
return Json(receiveSender, JsonRequestBehavior.AllowGet);
}
private void loadEditValues(Models.Model current)
{
int selected = current.GNR_FK;
IDataReader sender = current.getSender(selectedCustomer);
Models.Widget.Combo SenderNA = new Models.Widget.Combo();
List<Models.Widget.Combo> receiveSender = new List<Models.Widget.Combo>();
SenderNA.valueID = 0;
SenderNA.descriptionText = "NA";
receiveSender.Add(SenderNA);
while (sender.Read())
{
Models.Widget.Combo newItem = new Models.Widget.Combo();
newItem.valueID = int.Parse(sender["PK"].ToString());
newItem.descriptionText = sender["SURNAME"].ToString();
receiveSender.Add(newListItem);
ViewData["List"] = receiveSender;
}
}
Script:
function onSelect(e) {
var dataItem = this.dataItem(e.item);
var PK = dataItem.valueID;
$.ajax({
type: 'POST',
url: '/Project/loadValues',
data: "{'PK':'" + PK + "'}",
contentType: 'application/json; charset=utf-8',
success: function (result) {
$("#CNT_FK").data("kendoDropDownList").dataSource.data(result);
},
error: function (err, result) {
alert("Error" + err.responseText);
}
});
}
Regards
Problem Solved!
It was missing the select method to automatically select the first item after changing data!
success: function (result) {
var dropdown = $("#CNT_FK").data("kendoDropDownList");
dropdown.dataSource.data(result);
dropdown.select(0);
},
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'
I'm testing MVC for a demo and I managed to scrap together some pieces but now I am having trouble with an Html.ActionLink. The intent is to present the user with a series of dropdownlists that they must select before the ActionLink is shown. To do that I've copied some JQuery to hide/show my dropdownlists (as selections are made) and the ActionLink. I added an alert to my JQuery to check my values and via the alert it all looks good. But if I debug the controller the parm values are defaulted to 0. I'm not sure what code to include but I will try to include the relevant parts. I think it's something basic.
Here are the dropdown lists and ActionLink.
#Html.DropDownListFor(m => m.selected_env_ID, new SelectList(Model.Environments, "env_ID", "env_DESC"), "*Select an environment")
#Html.DropDownListFor(m => m.selected_app_ID, new SelectList(Model.Applications, "app_ID", "app_DESC"), "*Select an application",new { #hidden = "hidden" })
#Html.DropDownListFor(m => m.selected_job_ID, Enumerable.Empty<SelectListItem>(), "*Select a job", new { #hidden = "hidden" })
#Html.ActionLink("Submit", "Submit", new { id = Model.selected_job_ID, envid = Model.selected_env_ID }, new {id = "lnkSubmit" })
Here is the convoluted JQuery to hide/show and fill the cascading dropdowns.
<script>
$(document).ready(function ()
{
//Dropdownlist Selectedchange event
$("#selected_app_ID").change(function () {
var id = $('#selected_app_ID').val(); // id value
if (id == 0) {
$('#selected_job_ID').hide();
} else {
$('#selected_job_ID').show();
$("#selected_job_ID").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("SelectJobs")',
dataType: 'json',
data: { id: $("#selected_app_ID").val() },
success: function (jobs) {
// jobs contains the JSON formatted list of jobs passed from the controller
$("#selected_job_ID").append('<option value=0>*Select a job</option>');
$.each(jobs, function (i, job) {
$("#selected_job_ID").append('<option value="'
+ job.job_ID + '">'
+ job.job_DESC + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve jobs.' + ex);
}
});
}
return false;
});
//ddl select change
$("#selected_env_ID").change(function () {
var name = $('#selected_env_ID option:selected').text(); //Item1
var id = $('#selected_env_ID').val(); // id value
if (id == 0) {
$('#divSubmit').hide();
$('#selected_app_ID').hide();
$('#selected_job_ID').hide();
} else {
$('#selected_app_ID').show();
}
});
//ddl select change
$("#selected_job_ID").change(function () {
var name = $('#selected_job_ID option:selected').text(); //Item1
var id = $('#selected_job_ID').val(); // id value
var envid = $('#selected_env_ID').val(); // id value
if (id == 0) {
$('#divSubmit').hide();
} else {
$('#divSubmit').show();
alert("envid=" + envid + " jobid=" + id);
}
});
}); // end document ready
</script>
My controller has this and id and envid end up being 0:
public ActionResult Submit(int id = 0,int envid = 0) {
If I need to include something else just let me know.
Here is the method that fills the job dropdown list. This works without issues. It's the Html.ActionLink call to Submit that fails to include the parameters.
public JsonResult SelectJobs(int id)
{
db.Configuration.ProxyCreationEnabled = false;
IEnumerable<t_job> jobs = db.t_job.Where(j => j.app_ID == id).ToList();
return Json(jobs);
}
Your link
#Html.ActionLink("Submit", "Submit", new { id = Model.selected_job_ID, envid = Model.selected_env_ID }, new {id = "lnkSubmit" })
is rendered on the server side before you make any selection in the dropdowns. If the initial values of selected_job_ID and selected_env_ID are zero or null, then those values will be passed to the controller (have a look at the rendered html).
If you want to pass the values selected in you drop downs, you could either modify the links href attribute in the drop down change events, or create a button instead of a link, and do a redirect in the buttons click event based on the dropdown values.
You need to use JSON.stringify():
data: JSON.stringify({ id: $("#selected_app_ID").val() }),