Update ViewBag dropdownlist with ajax - ajax

I am working on cascaded dropdownlist with data passed with dataview.
Controller:
public ActionResult Index()
{
ViewBag.States = new SelectList(db.PLStates, "PLStateID", "PLStateName");
ViewBag.Cities = new SelectList(db.PLCitys, "PLCityID", "PLCityName");
return View();
}
[HttpPost]
public JsonResult GetCity(int SelectedStateId)
{
SelectList result = new SelectList(db.PLCitys.Where(x => x.PLStateID == 3), "PLCityID", "PLCityName");
return Json(result);
//return Json(ViewBag.Cities = new SelectList(db.PLCitys.Where(x => x.PLStateID == 3), "PLCityID", "PLCityName"));
}
HTML:
<script type="text/javascript">
$(document).ready(function () {
$("#States").change(function () {
var SelCity1 = $("#States").val();
$("#Cities").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetCity")',
dataType: 'JSON',
data: { SelectedStateId: SelCity1 },
success: function (Cities) {
ViewBag.Cities = Cities;
$("#Cities").append('Cities');
alert("success" + Cities);
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
<div>
#Html.DropDownList("States", "Select one")
#Html.DropDownList("Cities", "Select one")
</div>
In alert i can see the json gives back objects but the Cities dropdownlist becomes emptied with no value inside. Why ddl.cities is not filled with retured values??
Additional question is how to add style to dropdownlist??

You will have to manually add options to the cities drop down via js with the Json data returned from the controller.
As far as styling. You can style in inline by adding a "style"= to the html attributes or style with external css class using the #class html attribute.

Related

ASP.NET Core Razor Pages Ajax grid with Ajax request issue

I got Main View which contains table, on row click ajax request will be send.
$.ajax({
url: `/home/setViewBag/${id}`,
type: "get",
success: function (msg) {
$("#modal").html("");
$("#modal").append(msg);
modal.style.display = "block";
},
});
"SetViewBag"
[HttpGet]
[Route("setViewBag/{id}")]
public async Task<ActionResult> SetViewBag(int id)
{
ViewBag.Id = id;
return View("AjaxGrid");
}
AjaxGrid.cshtml
#using NonFactors.Mvc.Grid
#Html.AjaxGrid(
Url.Action("TestMethod", "Main", new { Id = ViewBag.Id }))
"TestMethod"
[HttpGet]
[Route("TestMethod/{id}")]
public async Task<ActionResult> TestMethod(int id)
{
return PartialView(await _service.Get(id));
}
PROBLEM: Ajax request append to my modal new div without TABLE
<div class="mvc-grid" data-url="/main/testMethod/1"></div>
As you can see on image, modal is empty
Modal should contains rendered table
#Html.Grid(Model).Build(columns =>
{
columns.Add(model => model.Id).Titled("Id");
columns.Add(model => model.Name).Titled("Name");
}).Pageable(pager =>
{
pager.PageSizes = new Dictionary<Int32, String> {{0, "All"}, {1, "1"}, {20, "20"}};
pager.ShowPageSizes = true;
pager.PagesToDisplay = 3;
pager.CurrentPage = 1;
pager.RowsPerPage = 1;
})
App: Asp.Net CORE 3.1
MVC-Grid v6.2.4
First of all there is a problem with your ajax call. You would like to return html to put it in your modal.
$.ajax({
url: `/home/setViewBag/${id}`,
type: "get",
dataType: 'html',
success: function (msg) {
$("#modal").html("");
$("#modal").append(msg);
modal.style.display = "block";
},
});
Then in controller you should return PartialView instead of View. I am not familiar with component you are using, but if it returns table you should just use in your success function $('#modal').html(msg); . If data is correctly returned from conroller and modal dialog is still empty, there is a problem with your modal setup. Make sure where you put your data.

Asp.net core controller function with return partial view with select2 not working and remote function validation is not firing in modal popup

Select2 is not working and remote validation is not firing, this is only happens when I convert the code to modal popup but if not everything is working properly. What Am I missing in my code? Any advise or help much appreciated.. Thank you
Here is my code the modal:
$('#tbProducts tbody').on('click', 'button', function () {
var data = productsTable.row($(this).parents('tr')).data();
//alert(data.id);
$.ajax({
url: '#Url.Action("Edit", "Products")',
type: 'GET',
data: { id: data.id },
success: function (result) {
$('#EditUnitModal .modal-content').html(result);
$('#EditUnitModal').modal()
}
});
});
Here is the controller edit code:
public async Task<IActionResult> Edit(int? id)
{
//code here
return PartialView("__Edit", product);
}
And here is my partial view __Edit code:
#model intPOS.Models.Master.ViewModel.ProductViewModel
//code here
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(function () {
$('#Unit').select2({
theme: 'bootstrap4',
dropdownParent: $('#EditUnitModal')
})
$('#Category').select2({
theme: 'bootstrap4',
dropdownParent: $('#EditUnitModal')
})
})
</script>
}
And View model code:
[Display(Name = "Product Code"), Required]
[Remote("CheckProduct", "Products", AdditionalFields = "Id", ErrorMessage = "Product already exists.")]
public string ProductCode
{
get
{
return _productcode;
}
set
{
_productcode = value.Trim();
}
}
Sample screen for not firing validation and select2 is not working:
sections aren't allowed in partial views. You can still use modals and partial views via Ajax for edit forms but there is a small modification you need to do in order for this to work:
Include all the necessary scripts in your page (this is mandatory as sections aren't allowed in partial views).
In your javascript code add these lines in order to parse the new form via jquery validation unobtrusive and your select elements via Select2.
$('#tbProducts tbody').on('click', 'button', function () {
var data = productsTable.row($(this).parents('tr')).data();
//alert(data.id);
$.ajax({
url: '#Url.Action("Edit", "Products")',
type: 'GET',
data: { id: data.id },
success: function (result) {
$('#EditUnitModal .modal-content').html(result);
//Here we parse the new form via jquery validation unobtrusive.
$.validator.unobtrusive.parse($('#EditUnitModal .modal-content form')[0]);
//Here we initialize select2 for the selected elements.
$(".yourSelect2ElementClass").select2({//options...});
//Now we launch the modal.
$('#EditUnitModal').modal()
}
});
});
Don't forget to remove the section from your partial view and include your scripts in the containing view.

Can't load data using Ajax for Razor Pages

I have this ajax call in my view, Form.cshtml
<form id="myForm">
<input id="btnSubmit" type="submit" value="Load data" />
<p id="result"></p>
</form>
#section scripts{
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
debugger
$.get('/Form/',function (data) {
debugger
console.log('test');
});
})
});
</script>
}
and in my Razor Pages code behind, Form.cshtml.cs
public class FormModel : PageModel
{
public JsonResult OnPost()
{
List<Student> students = new List<Student>{
new Student { Id = 1, Name = "John"},
new Student { Id = 2, Name = "Mike"}
};
return new JsonResult(students);
}
}
The problem is it doesn't reach OnPost method. If I put in OnGet, it will automatically load before I click the Submit button.
I try to create another Razor page called Filter.cshtml and in Filter.cshtml.cs. And then in my Form.cshtml, I changed my url to /Filter/, it did reach OnGet in Filter.cshtml.cs
public class FilterModel : PageModel
{
public JsonResult OnGet()
{
List<Student> students = new List<Student>{
new Student { Id = 1, Name = "John"},
new Student { Id = 2, Name = "Mike"}
};
return new JsonResult(students);
}
}
The default behaviour of clicking a submit button in a form is that the form gets submitted. At the moment, your form has no method specified, so the submission will default to the GET method. If you want to submit the form by AJAX POST rather than the usual behaviour, you need to do two things:
Cancel the default action of the button click (which is what currently causes the OnGet handler to execute)
Change the jQuery code to use the POST method:
#section scripts{
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function (e) { // include the event parameter
e.preventDefault(); // prevents the default submission of the form
$.post('/Form/',function (data) { // change from 'get' to 'post'
console.log('test');
});
});
});
</script>
}
the $.get() makes Ajax requests using the HTTP GET method, whereas the $.post() makes Ajax requests using the HTTP POST method.
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/Filter/OnGet",
success: function (result) {
}
});

how to return table on ajax call in mvc

I am new in MVC. I have a DropDown in index view and i want to show entire table basis on selected item from dropdown. I fire ajax on onChange function of dropdown using jQuery.
$(document).ready(function () {
$("#ddlUser").change(function () {
$("#ddl2").empty();
$.ajax({
type: "POST",
url: '#Url.Action("getState")',
dataType: "json",
data: { id: $("#ddlUser").val() },
success: function (city) {
},
error: function (ex) {
alert('failed to retrieve' + ex);
}
})
});
return false;
});
and i get data from database using this code
public JsonResult getState(int id)
{
MvcDemo9Feb.Models.ModelData MD = new Models.ModelData(); //MD is object of model and dt is DataTable type property
MD.dt = obDB.getCity(id);//obDB is class and getCity is method of it that return datatable
return Json(MD);
}
here i don't know how to bind data of model object MD to table on view. Please suggest something

MVC pass JSON ViewModel to View

I have an MVC application that I'm using various JsonResult endpoints to populate the javascript ViewModel.
I have been using several jQuery Ajax requests to populate the model, but I'd like as much of the inital model to be passed to the view on the server.
The ViewModel has 3-5 pieces (depending on where the user is in the application):
Basic page links, these don't change very often and could be the exact same throughout the entire user's session
User notifications.
User data.
(optional) Viewable data
(optional) misc data
I'm currently using this code to load the first three pieces:
$(document).ready(function () {
ko.applyBindings(viewModel);
#Html.Raw(ViewBag.Script)
// Piece 1. Almost always the same thing
postJSON('#Url.Action("HomeViewModelJson", "Home")', function (data) {
if (data == null)
return;
for (var i in data.Tabs) {
viewModel.tabs.push({ name: data.Tabs[i] });
}
for (var i in data.Buttons) {
viewModel.metroButtons.push({ name: data.MetroButtons[i] });
}
for (var i in data.Ribbons) {
viewModel.ribbons.push(data.Ribbons[i]);
}
ApplyButtonThemes();
});
});
// Piece 2. Changes constantly. OK as is
postJSON('#Url.Action("GetNotifications", "NotificationAsync")', function (nots) {
viewModel.notifications.removeAll();
ko.utils.arrayForEach(nots, function (item) {
item.readNotification = function () {
hub.markNotificationAsRead(this.Id);
return true;
};
viewModel.notifications.push(item);
});
});
// Piece 3. Changes but should also be loaded at startup
postJSON('#Url.Action("GetUser", "UserAsync")', function (user) {
viewModel.user(koifyObject(user));
});
postJSON = function(url, data, callback) {
if($.isFunction(data)) {
callback = data;
data = {};
}
$.ajax({
'type': 'POST',
'url': url,
'contentType': 'application/json',
'data': ko.toJSON(data),
'dataType': 'json',
'success': callback
});
};
I tried doing something like this, but I'm finding that by using the #Html.Action("HomeViewModelJson", "Home") is causing the HTTP headers to get changed and the whole page is sent as if it were JSON
(function (data) {
if (data == null)
return;
for (var i in data.Tabs) {
viewModel.tabs.push({ name: data.Tabs[i] });
}
for (var i in data.MetroButtons) {
viewModel.metroButtons.push({ name: data.MetroButtons[i] });
}
for (var i in data.Ribbons) {
viewModel.ribbons.push(data.Ribbons[i]);
}
ApplyMetroButtonThemes();
})('#Html.Action("HomeViewModelJson", "Home")');
What I'd like to do is use the existing JsonResult endpoints to get Json data into my ViewModel on the server side, before the page is sent to the user.
Are there any options that will allow me to do that w/o rewriting my controllers?
When rendering the main view you are using a view model, right? In this view model simply populate the properties that you don't want to be fetched with AJAX before returning the view:
public ActionResult Index()
{
MyViewModel model = ...
model.Prop1 = ...
model.Prop2 = ...
return View(model);
}
for example if you have the following action that is used for the AJAX requests:
public JsonResult GetProp1()
{
Property1ViewModel model = ...
return Json(model, JsonRequestBehavior.AllowGet);
}
you could use it from the main action to populate individual properties:
model.Prop1 = (Property1ViewModel)GetProp1().Data;
model.Prop2 = (Property2ViewModel)GetProp2().Data;
and then inside the corresponding view you could use the Json.Encode method to serialize the entire model into a JSON string:
#model MyViewModel
<script type="text/javascript">
var model = #Html.Raw(Json.Encode(Model));
// You could use model.Prop1 and model.Prop2 here
</script>
or you could also serialize individual properties if you don't need all of them:
#model MyViewModel
<script type="text/javascript">
var prop1 = #Html.Raw(Json.Encode(Model.Prop1));
</script>

Resources