I have two buttons:
<center>
<p><button id="newuserbutton" >Create New User</button>
<p><button id="edituserbutton" >Edit User</button>
</center>
Clicking any of these button opens 'form1' over popup dialog using jQuery click function:
<script type="text/javascript">
// On DOM ready (this is equivalent to your $(document).ready(function () { ...} )
$(function() {
// Initialize modal (only once) on #div1
$('#div1').dialog({
modal: true,
autoOpen: false,
minHeight: 300
});
// Bind click on #newuserbutton button
$('#newuserbutton').click(function() {
$('#div1')
// Set buttons
.dialog("option", "buttons", [
{ text: "Create User", click: function() { $(this).dialog(""); } },
{ text: "Cancel", click: function() { $(this).dialog("close"); } }
])
// Set modal title
.dialog('option', 'title', 'Create new user')
// Set modal min width
.dialog({ minWidth: 550 })
// Open modal
.dialog('open');
});
// Bind click on #edituser button
$('#edituserbutton').click(function () {
$('#div1')
// Set buttons
.dialog("option", "buttons", [
{ text: "Save Changes", click: function() { $(this).dialog(""); } },
{ text: "Delete", click: function() { $(this).dialog("alert"); } },
{ text: "Cancel", click: function() { $(this).dialog("close"); } }
])
// Set modal title
.dialog('option', 'title', 'Edit User')
// Set modal min width
.dialog({ minWidth: 500 })
// Open modal
.dialog('open');
});
})
</script>
I need to use buttons (not above two) on dialog such as; "Create User", "Delete" etc. to manage my behind-code click events to manipulate a database. How i can do it? Thank you.
You could use an ajax call that can pass the data to the server and manipulate it there.
Steps
1.Create an asmx in your WebApplication (Add New Item > WebService) and name it MyService.asmx
2.Change the code-behind like this (it will be here - App_Code/MyService.asmx.cs)
using System.Web.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class MyService : System.Web.Services.WebService
{
[WebMethod]
public string CreateUser(string userName, string password)
{
//here you can do all the manipulations with your database
return userName + " - " + password;
}
}
3.Now in the Create User Button's click event write this.
click: function () {
var DTO = {
userName: $("#username").val(),
password: $("#password").val()
};
$.ajax({
type: 'POST',
data: JSON.stringify(DTO),
url: "MyService.asmx/CreateUser",
contentType: 'application/json'
}).done(function (result) {
//check whether the result is wrapped in d
var msg = result.hasOwnProperty("d") ? result.d : result;
alert(msg);
}).fail(function (xhr) {
alert('Error: ' + xhr.statusText);
return false;
});
}
This is one way of doing it.
you can use the httphandler. you can create the method to update/Create User in handler and that method.you can call by using Jquery.
function CallHandler() {
$.ajax({
url: "Handler/MyHandler.ashx",
contentType: "application/json; charset=utf-8",
data: { 'Id': '10000', 'Type': 'Employee' },
success: OnComplete,
error: OnFail
});
return false;
}
Following code will be in handler.
public class MyHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
CreateUser();
}
public bool IsReusable {
get {
return false;
}
}
private Employee CreateUser()
{
}
}
When you call the Httphandler from jquery.It will hit to ProcessRequest. there you can perform code behind operation.
Try Adding runat="server" & onclick="function()" in button like :
<center>
<p><button id="newuserbutton" runat="server" onclick="function1()">Create New User</button>
<p><button id="edituserbutton" runat="server" onclick="function2()">Edit User</button>
</center>
Hope it can help.
If not, Another way can be to using ajax:
add onclick=ajaxcall()
2- in Javascript, add ajax call like:
`ajaxcall= function()
{
$.ajax({
type: "GET",
url: "youraspxpage.aspx/MethodName?data=AnyDataAsQueryString",
success: function(data){
$("#resultarea").text(data);
}
});
}`
OR
ajaxcall= function()
{
$.ajax({
type: "POST",
url: "youraspxpage.aspx/MethodName",
data:data,
success: function(data){
$("#resultarea").text(data);
}
});
}
3- Based on get or post use HttpGet or HttpPost attribute on public MethodName in code behind.
OR
alternatively try PageMethods, Check this link for more detail about pagemethods.
Related
This is my Controller :
public JsonResult Success() { return Json(new { Success = true, Message = "Data Added Succefully" }); }
public JsonResult Error(string message) { return Json(new { Success = false, Message = message }); }
[HttpPost]
public JsonResult CreateAjax(TAUX taux)
{
if (ModelState.IsValid)
{
try
{
foreach (short i in taux.SelectItems)
{
taux.CAT_ID = i;
db.TAUX.Add(taux);
db.SaveChanges();
}
return Success();
}
catch (Exception err)
{
return Error(err.Message);
}
}
ViewBag.CAT_ID = new SelectList(db.CATEGORIE, "CAT_ID", "LIBELLE", taux.CAT_ID);
ViewBag.C_GARANT = new SelectList(db.GARANTIE, "C_GARANT", "LIB_ABREGE", taux.C_GARANT);
return Error("The server wasn't able to do something right now.");
}
This is My PartialView CreateAjax:
#model pfebs0.Models.TAUX
....
#using (Html.BeginForm("CreateAjax", "Taux", FormMethod.Post, new { id = "form" }))
{...}
And this is my View Index :
#model IEnumerable<pfebs0.Models.TAUX>
...
<script>
$.ajax({
url: "/",
method: "POST",
data: getMyData(),
success: function (json) {
if (json.Success) {
alert("Wow, everything was fine!");
} else {
alert(json.Message);
}
},
// This will be trigered whenever your ajax call fails (broken ISP link, etc).
error: function () {
alert("Something went wrong. Maybe the server is offline?");
}
});
</script>
...
#Html.ActionLink("Ajouter", "Create", "Taux",
new { id = "btnAdd", #class="btn btn-default"})
</p>
...
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function () {
$.ajaxSetup({ cache: false });
$('#btnAdd').click(function () {
$('.modal-dialog').load(this.href, function () {
$('#modalDiv').modal({
backdrop: 'static',
keyboard: true
}, 'show');
});
return false;
});
});
....
</script> }
What I'm trying to do here is to show success alert after Insertionn but after Insertion I'm redirected to new Page Localhost/Taux/ajaxCreate where It show me this message {"Success":true,"Message":"Data Added Succefully"} instead of showing PopUp with success message in Index Page. What's wrong here ?
You should use
#using (Ajax.BeginForm(....))
{ }
with the appropiate parameters.
See How can I return a JSON result to a Ajax.BeginForm for details.
There might be some issues with the script as well.
What are you trying to do with:
<script>
$.ajax({
url: "/",
method: "POST",
data: getMyData(),
?
UPDATE
Ok, this should work:
1) use your original
#using (Html.BeginForm
2) put the ajax call in a function:
<script type="text/javascript">
function postData()
{
$.ajax({
url: '#Url.Action("CreateAjax", "Taux")',
method: "POST",
data: $('#form').serialize(),
....
}
3) change the type="submit" to type="button" at the submit button and add:
onclick="postData()"
attribute.
4) change ajax url:
url: '#Url.Action("CreateAjax", "Taux")',
5) add the change the getMyData function function
data: $('#form').serialize(),
I have a MVC4 single page website with a form. The loading of the contents is achieve with ajax. I do not know how to get the data out from JSON in C#? Here is my code:
JavaScript:
$("#subnt").click(function (event) {
event.preventDefault();
var url = "/Home/Submit";
$.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
if (data.Success === true) {
$("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal'); // loads the page into 'min-content' section
}
else {
// display error message
}
})
});
});
C#:
[HttpPost]
public JsonResult Submit()
{
return Json(new { Success = true, SomeOtherData = "testing" });
}
Please check below working code -
I have used exactly your working code -
[HttpPost]
public JsonResult Submit()
{
return Json(new { Success = true, SomeOtherData = "testing" });
}
Then I used following JQuery to hit the above action -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$('#click').click(function (e) {
$.ajax({
url: "#Url.Action("Submit")",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response);
},
success: function (data) {
if (data.Success == true)
alert(data.SomeOtherData);
}
});
});
});
</script>
<input type="submit" value="click" id="click" />
And as the output I was able to get an alert as shown below -
Easiest thing to do is use the superior json.net
[HttpPost]
public string Submit()
{
var result = new { success = true, someOtherDate = "testing"};
var json = JsonConvert.SerializeObject(result);
return json;
}
Your code is ok bu you can add debugger.and open developer tools check your data .
$.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
debugger;
if (data.Success === true) {
$("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal'); // loads the page into 'min-content' section
}
else {
// display error message
}
No, the other way around. How to retrieve the data from the form (json).
I have a jquery ui dialog that has a radio button list on it. I need to call a server side method when the user clicks ok and I need to pass the selected value. I tried doing it by calling an ajax method on and passing the selected value as a parameter. This worked great (the value was passed) but I could not access a cookie from the method (got error - Request is not available in this context), which makes sense being that this is an ajax request. Here is the code:
$("#dialogReject").dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Reject": function () {
var value = $(this).find('input:checked').val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/myPage.aspx/RejectDocumentWM",
data: "{'rejectReason':'" + value + "'}",
dataType: "json",
success: function (data) {
alert('success');
},
error: function (result) { alert('error'); }
});
$(this).dialog('close');
},
Cancel: function () {
$(this).dialog("close");
}
}
});
RejectDocument():
[WebMethod]
public static void RejectDocumentWM(string rejectReason)
{
MyNamespace.myPage page = new MyNamespace.myPage();
page.RejectDocument(rejectReason);
}
protected void RejectDocument(string rejectReason)
{
batch batch = (batch)Session["Batch"];
if (client.RejectDocument(batch.GetCurrentDoc().icn, rejectReason, Request.Cookies["username"].Value)) //here is where I get the error
{
NextDocument();
}
}
I tried doing it by putting the value into a hidden field and then calling a button click which calls a server side method. My problem here was that the hidden field's value was always blank even though it set properly in the client script. Here is the code for that:
$("#dialogReject").dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Reject": function () {
var value = $(this).find('input:checked').val();
$('[id$="hdfRejectReason"]').val(value); //this sets properly
$('[id$="btnRejectDoc"]').click();
$(this).dialog('close');
},
Cancel: function () {
$(this).dialog("close");
}
}
protected void btnRejectDoc_Click(object sender, EventArgs e)
{
batch batch = (batch)Session["Batch"];
if (client.RejectDocument(batch.GetCurrentDoc().icn, hdfRejectReason.Value, Request.Cookies["username"].Value))
//hdfRejectReason.Value is blank
{
NextDocument();
}
}
Any ideas for me? I am at my wits end.
Thanks!
First of All, is this hf is in 'popup' or in 'main page' section?
Second, in stackoverflow, we discused and set other (better?) way to set hidden field value in jQuery:
<div class="hfFoo-wrap">
<asp:HiddenField runat="server" ID="hfFoo" />
</div>
function FooBarFunction() {
var hfFoo = $('.hfFoo-wrap input[type=hidden]');
hfFoo.val('Bar');
var isBar = hfFoo.val();
}
Maybe in btnRejectDoc_Click have other 'null' or 'empty' params?
Third: I prefere FrameDialog with 'aspx' page and 'callback delegate'.
create popup as 'aspx' page
open popup from 'main page' by jQuery as jQuery.FrameDialog
close dialog from 'aspx-popup' as 'close popup' (jQuery.FrameDialog.closeDialog();)
on 'main page' catch callback delegate (with params from popup) and set hidden field there
I have a partial view that contains all my buttons and it needs to display updated values after a form is submitted. At the submission I already have it rendering another partial view, is there a way to make it work where on success of that one being rendered it re-renders. Here is the code I am trying to get to work now based on what I've seen in other places.
jQuery in my view:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$('#ChangeGrade').click(function (e) {
var tdata = $('#form1').serialize();
var origname = $('#HeatGradeDiv').find('input[name="grade"]').first().val();
var newname = $('#HeatGradeDiv').find('input[name="updatedGrade"]').first().val();
var heatname = $('#HeatGradeDiv').find('input[name="hiddenHeat"]').first().val();
$.ajax({
type: "POST",
data: {
mCollection: tdata,
grade: origname,
updatedGrade: newname,
hiddenHeat: heatname
},
url: '#Url.Action("ChangeGrade","Home")',
success: function (result) { success(result); }
});
});
function success(result) {
$('#HeatGradeDiv').dialog('close');
$("#Partial_Chem_Analysis").html(result);
//ajax call I'm trying to get working
$.ajax({
type: "POST",
url: "/Home/ButtonsPartial",
success: function (result2) { $("#ButtonsPartial").html(result2); }
});
}
});
</script>
Here is the controller method I'm calling. When I run it now it is not getting hit.
public ActionResult ButtonsPartial()
{
ButtonsModel B = new ButtonsModel();
B.GetData(searchQ);
return PartialView(B);
}
Any help is appreciated.
If you attach it to a debugger such as (chrome developer tools or firebug) are you seeing any http or js errors?
It looks like you might need to make it a GET rather than POST...
$.ajax({
type: "GET",
url: "/Home/ButtonsPartial",
success: function (result2) { $("#ButtonsPartial").html(result2); }
});
If I add a serverside function in masterlayout, the popup will display in all the pages. However, once I click the "no" button, it doesn't show anymore. For that, I have to use session, but we can't set the session value in jQuery.
The code behind I use in masterlayout is:
<script runat="server">
protected void btnCancel_Click(object sender, EventArgs e)
{
Session["sesvalue"] = 1;
}
</script>
but the method doesn't fire on button click
Your method must have static atribute.
[WebMethod]
public static string MethodName()
{
return "";
}
The way to call a server-side function from jQuery is via an ajax request. You don't need to put anything in Session, you can simply pass the value from the client side as an parameter to the function on the server side. Here's an example:
function ShowDialogAndCallServerSideFunction()
{
var $dialog = $('<div class="dialog"></div>')
.html('Dialog content goes here')
.dialog({
autoOpen: false,
width: 320,
title: 'Title goes here',
closeOnEscape: true,
buttons: [
{
text: "No",
click: function() { $(this).dialog("close"); }
},
{
text: "Yes",
click: function() {
$.ajax({
"type": "POST",
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"url": "WebServiceUrl.asmx/MethodName",
"data": "{'parameter': " + your_parameterHere + " }",
"success": function(result) {
//handle success here
},
"error": function(xhr, ajaxOptions, thrownError) {
//handle any errors here
}
});
$(this).dialog("close");
}
}
]
});
$dialog.dialog('open');
}
On the server side, you can have a Web Service - called WebServiceUrl on my example-:
[WebMethod]
public void MethodName(string parameter)
{
//the value received in 'parameter' is the value passed from the client-side via jQuery
}