In my ASP.NET MVC project i have the following situation:
An ExController with this action:
public ActionResult Index()
{
//Get Data from Repository
return View(Model);
}
In the Ex View folther i have a Index.cshtml and a _PartialIndexGrid.cshtml.
In the Index i have a ribbon menu with a checkbox, and when i click on it i would like to refresh just the grid placed on the _PartialIndex.cshtml, is it possible?
The Index View:
//Ribbon Code here
#Html.Partial("_PartialIndexGrid", Model)
<script>
if (e.parameter) {
$.ajax({
url: '#Url.Action("Index")',
type: "get",
success: function (result) {
$("_PartialIndexGrid").html(result);
},
failure: function () {
alert('error');
}
});
</script>
This script actually do the ajax request, but is not reloading the grid partial view.
Thanks.
Create a container div and on checkbox change check if its checked reload the partial view via ajax call like this:
<div id="PartiaContainer">
#Html.Partial("_PartialIndexGrid", Model)
</div>
<input type="checkbox" id="checkbox1"/>
<script>
$('#checkbox1').change(function(){
if(this.checked)
{
$.ajax({
url: '#Url.Action("Index")',
type: "get",
success: function (result) {
$("#PartialContainer").html(result);
},
failure: function () {
alert('error');
}
});
}
});
</script>
Related
I have placed a bootstrap toggle switch in my application
Now i want is to send the On and Off values to my action method
Bellow is my razor syntax
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset style="height:60px">
<legend style="text-align:center; font-size:large; font-family:'Times New Roman'; background-color:#C8E6C9; color:red">Remote On/Off</legend>
<input id="test_id" name="cmdName" type="checkbox" checked data-toggle="toggle">
</fieldset>}
For passing data to controller from JS i have searched many articles and found that ajax is the way to do it
Bellow is my script for ajax inside JS
<script>
var cmdName = '#Session["cmdName"]';
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
$.ajax({
url: '#Url.Action("MultiGraph")',
type: 'Post',
data: 'On',
success: function () {
alert(data)
}
});
} else {
$.ajax({
url: '#Url.Action("MultiGraph")',
type: 'Post',
data: 'Off',
success: function () {
alert(data)
}
});
}
}); </script>
I have also used session variable but getting null value in it
Bellow is my controller code
public ActionResult MultiGraph(string search, string start_date, string End_date, string cmdName, int? page)
{
//search contain serial number(s)
//cmdName is for input checkbox
}
Bellow is the image for my switch button
When i switch it to Off then this Off string should be sent to my action method and vise versa
Updated Code
After reading comments i have done the following changes to my code
I have added a new action method of type Post
[HttpPost]
public ActionResult ToggleSwitch (string search, string cmdName)
{
List<SelectListItem> items = new List<SelectListItem>();
var dtt = db.ADS_Device_Data.Select(a => a.Device_Serial_Number).Distinct().ToList();
foreach (var item in dtt)
{
if (!string.IsNullOrEmpty(item))
{
items.Add(new SelectListItem { Text = item, Value = item });
}
}
ViewBag.search = items;
return View();
}
Bellow are changes in my razor
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "On"}',
success: function () {
alert(data)
}
});
} else {
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "Off"}',
success: function () {
alert(data)
}
});
}
});
But still i get no alert message, when i inspect element i found this error
I am stuck to this problem from almost 2 days
Any help would be appreciated
You need to use the $ character to invoque jQuery functions and pass your data from page to controller with the same name you defined in the action method using Json notation:
'{"cmdName": "On"}',
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "On"}',
success: function () {
alert(data)
}
Furthermore, you might need to decorate your mvc action whith the [HttpPost] attribute.
Trying to figure out how to patch with ajax. I want the ajax to patch "something" when I press the btnUpdate button.
In my router:
Route::patch('forecasts/edit/{id}',['as'=>'forecasts.edit',
'uses'=>'forecastsController#handleEdit']);
In my controller:
public
function handleEdit($id)
//handle edit form submission
{
$data=Input::all();
return $data; //just want to see something
}
In my view html:
<div>
<button type='button'id="btnUpdate" name="btnUpdate">Update</button>
</div>
In my view script:
$("#btnUpdate").click(function () {
$.ajax({
type: "PATCH",
url : base_url+'/forecasts/edit/'+forecast_id,
data : "Something", success: function (data) {
alert(data);
}
});
});
your ajax url seem to be wrong. Try to use helper function like route.
$.ajax({
url : "{{route('forecasts.edit',forecast_id)}}",
}
});
});
Url Pattern for edit would be like htt://base_url/somefunction/{id}/edit
Index.html (View)
<div class="categories_content_container">
#Html.Action("_AddCategory", "Categories")
</div>
_AddCategory.cshtml (PartialView)
<script>
$(document).ready(function () {
$('input[type=submit]').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '#Url.Action("_AddCategory", "Categories")',
dataType: "json",
data: $('form').serialize(),
success: function (result) {
$(".categories_content_container").html(result);
},
error: function () {
}
});
});
});
</script>
#using (Html.BeginForm())
{
// form elements
}
Controller
[HttpPost]
public ActionResult _AddCategory(CategoriesViewModel viewModel)
{
if(//success)
{
// DbOperations...
return RedirectToAction("Categories");
}
else
{
// model state is not valid...
return PartialView(viewModel);
}
}
Question: If operation is success I expect that redirect to another page (Categories). But no action, no error message. If operation is not success, it is working like my expected.
How can I do this? How can I route another page with using AJAX post?
Don't redirect from controller actions that are invoked with AJAX. It's useless. You could return the url you want to redirect to as a JsonResult:
[HttpPost]
public ActionResult _AddCategory(CategoriesViewModel viewModel)
{
if(//success)
{
// DbOperations...
return Json(new { redirectTo = Url.Action("Categories") });
}
else
{
// model state is not valid...
return PartialView(viewModel);
}
}
and then on the client test for the presence of this url and act accordingly:
$.ajax({
type: "POST",
url: '#Url.Action("_AddCategory", "Categories")',
data: $('form').serialize(),
success: function (result) {
if (result.redirectTo) {
// The operation was a success on the server as it returned
// a JSON objet with an url property pointing to the location
// you would like to redirect to => now use the window.location.href
// property to redirect the client to this location
window.location.href = result.redirectTo;
} else {
// The server returned a partial view => let's refresh
// the corresponding section of our DOM with it
$(".categories_content_container").html(result);
}
},
error: function () {
}
});
Also notice that I have gotten rid of the dataType: 'json' parameter from your $.ajax() call. That's extremely important as we are not always returning JSON (in your case you were never returning JSON so this parameter was absolutely wrong). In my example we return JSON only in the case of a success and text/html (PartialView) in the case of failure. So you should leave jQuery simply use the Content-Type HTTP response header returned by the server to automatically deduce the type and parse the result parameter passed to your success callback accordingly.
The ajax call you made should not be able to redirect the whole page. It returns data to your asynchronous call only. If you want to perform a redirect, i
the javascript way to redirect is with window.location
So your ajax call should look like this:
<script>
$(document).ready(function () {
$('input[type=submit]').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '#Url.Action("_AddCategory", "Categories")',
dataType: "json",
data: $('form').serialize(),
success: function (result) {
window.location='#Url.Action("Categories")';
},
error: function () {
}
});
});
});
</script>
In you action method, instead of returning a partial or redirect, return Json(true);
public ActionResult _AddCategory(CategoriesViewModel viewModel)
{
if(//success)
{
return Json(true);
}
else
{
return Json(false);
}
}
I have a view with a few checkboxes that can be selected or unselected. I'd like to always register any change in a checkbox, without the use of a submit button (the user could forget to do it, and it would waste time).
So, is there a way to handle this inside the view? Up to now, I've only used the controller to do that job.
So, a piece of code :
#ModelType MvcApplication.OpportuniteDetails
#Code
ViewData("Title")="Details"
#End Code
<script type="text/javascript">
$(function () {
$(':checkbox').change(function() {
$.ajax({
url: '#Url.Action("update")',
type: 'POST',
data: { isChecked: $(this).is(':checked') },
success: function (result) { }
});
});
});
</script>
[... Some code here...]
#Html.Raw("Mail sent?") #Html.CheckBox(Model.Opportunite.Mail)
<input type="checkbox" name="mail" id="mail" onclick="test()" />
You could use AJAX:
$(function() {
$(':checkbox').change(function() {
var form = $(this).closest('form');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(result) {
}
});
});
});
In this example we subscribe to the change event of each checkbox. When this event is trigerred we look for the containing form and send its contents to the server using an AJAX request.
And if you only wanted to submit the current checkbox state to the server and not the entire form:
$(function() {
$(':checkbox').change(function() {
$.ajax({
url: '#Url.Action("SomeAction")',
type: 'POST',
data: { isChecked: $(this).is(':checked') },
success: function(result) {
}
});
});
});
where you could have a controller action which will do the necessary processing:
[HttpPost]
public ActionResult SomeAction(bool isChecked)
{
...
}
If you don't need or want AJAX and just want to submit the form, this
$(':checkbox').change(function() {
var form = $(this).closest('form');
form.get( 0 ).submit();
});
would do it.
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
GOTO = function () {
alert("yes");
$.ajax({
cache: false,
type: "POST",
url: "/Home/Index/",
data: datastring,
dataType: "json",
success: function (data) {
alert("Ohh Yaa Success");
}
});
}
</script>
<input type="button" value="submit" onclick="JavaScript:GOTO()" />
</asp:Content>
My Controller ActionResult is something like this
JsonResult
[HttpPost]
public System.Web.Mvc.JsonResult Index(FormCollection collection)
{
//return Content("<xml>this is just test</xml>", "text/xml");
//return Content("this is just test", "text/plain");
if (Request.AcceptTypes.Contains("application/json"))
{
return Json(new { id = 1, value = "new" });
}
else if (Request.AcceptTypes.Contains("application/xml") ||
Request.AcceptTypes.Contains("text/xml"))
{
}
if (Request.AcceptTypes.Contains("text/html"))
{
//return View();
}
return Json(new { foo = "bar", baz = "Blech" });
}
I am not able to return the JsonResult here allways I am getting popupmessage saying u have choosen to open this dialogue? is there something I am doing wrong?
thanks
Try this instead -- and make sure jQuery is loaded first. Note the changes to apply the handler via jQuery instead of inline, serializing the data, generating the URL in code dynamically rather than hard-coded, and returning false from the click handler to prevent normal form submission.
<script type="text/javascript">
$(function() {
$('input[type=button]').click( function() {
var data = $('form').serialize(); // or however you get your data
$.ajax({
cache: false,
type: "POST",
url: "<%= Html.Action( "index", "home" ) %>",
data: data,
dataType: "json",
success: function (data) {
alert("Ohh Yaa Success");
}
});
return false; // don't do the normal submit
});
});
</script>
<input type="button" value="submit" />
you need to put the button in a form tag and call the GOTO function in onsubmit event
It looks like your data: datastring might be the problem. Check to make sure that the name of your data parameter is the same as your method parameter.
I would try to approach it more like this ...
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(document).ready(function () {
$(form).submit(function() {
alert("yes");
$.post({
cache: false,
type: "POST",
url: "/Home/Index/",
data: datastring,
dataType: "json",
success: function (data) {
alert("Ohh Yaa Success");
}
});
});
}
</script>
<form>
// your form fields
<input type="button" value="submit" />
</form>
</asp:Content>
And then your controller should look more like this.
Notice how we changed the parameter to a string that matches your jQuery data field.
[HttpPost]
public System.Web.Mvc.JsonResult Index(string datastring)
{
// you can deserialize your Json here.
//return Content("<xml>this is just test</xml>", "text/xml");
//return Content("this is just test", "text/plain");
if (Request.AcceptTypes.Contains("application/json"))
{
return Json(new { id = 1, value = "new" });
}
else if (Request.AcceptTypes.Contains("application/xml") ||
Request.AcceptTypes.Contains("text/xml"))
{
}
if (Request.AcceptTypes.Contains("text/html"))
{
//return View();
}
return Json(new { foo = "bar", baz = "Blech" });
}