How to pass variable from jquery to code in c# - asp.net-mvc-3

in my page i have an int variable name mySerial and i want to pass a value from a script
mySerial =ui.item.Serial is not working

You could pass this variable as query string parameter to some controller action:
<script type="text/javascript">
var mySerial = '12345';
$.ajax({
url: '#Url.Action("Foo", "Home")',
type: 'POST',
data: { mySerial: mySerial },
success: function(result) {
alert('success');
}
});
</script>
and the Foo action:
[HttpPost]
public ActionResult Foo(string mySerial)
{
... do something with the serial here
}
Another possibility is to perform a redirect if you don't want to use AJAX:
<script type="text/javascript">
var mySerial = '12345';
var fooUrl = '#Url.Action("Foo", "Home")';
window.location.href = fooUrl + '?mySerial' + encodeURIComponent(mySerial);
</script>
Or maybe I misunderstood your question and you want to assign your javascript variable to some value coming from the view model? In this case:
<script type="text/javascript">
var mySerial = #Html.Raw(Json.Encode(Model.MySerial));
</script>

you could pass value from your jquery to controller action like this ...
$(document).ready(function()
{
var postdata = { name: "your name", Age: "your age" };// you can pass control values
$.ajax({
ur: /home/index,
data: postdata,
success: function(returndata)
{
// do something here for the return data...
}
});
});
in your controller
public ActionResult PostedDAta(string myname, string myage)
{
// do somethign here and return Json back to Jquery code
return Json(data,JsonRequestBehaviour.AllowGet);
}

Related

How to display update content after posting data by ajax in asp.net core entity framework core

I want to display update content after posting data by jquery ajax. I tried it but not display data.
here is my code...
jquery ajax
$(document).ready(function () {
$('#paid').click(function () {
var pid = $('#pid').val();
var amt = $('#amt').val();
var payType = $('#payType').val();
$.ajax({
type: "POST",
url: "/Reception/Registration/AddPaidBalance",
data: { PatientId: pid, PaidAmt: amt, PaymentType: payType },
success: function (data) {
}
});
});
})
controller
[HttpPost]
public async Task<IActionResult> AddPaidBalance(PatientBilling patientBilling)
{
if (ModelState.IsValid)
{
_db.PatientBilling.Add(patientBilling);
await _db.SaveChangesAsync();
//return RedirectToAction("Details", "Registration", new { area = "Reception", id = patientBilling.PatientId });
//return RedirectToAction("Details", "Registration", new { patientBilling.PatientId});
}
return View();
}
help me out from this issue.
Based on your code, you make ajax request to post data of PatientBilling to action method. To display new-added PatientBilling information on Details page after the request completes successfully, you can do redirection in success callback function, like below.
<script>
$(document).ready(function () {
$('#paid').click(function () {
var pid = 1;//$('#pid').val();
var amt = "amt";//$('#amt').val();
var payType = "type1";//$('#payType').val();
$.ajax({
type: "POST",
url: "/Reception/Registration/AddPaidBalance",
data: { PatientId: pid, PaidAmt: amt, PaymentType: payType },
success: function (data) {
window.location.href = "#Url.Action("Details", "Registration", new { Area = "Reception"})" + "?patientId=" + pid;
}
});
});
})
</script>
Details action
public IActionResult Details(int patientId)
{
// code logic here
// get details of PatientBilling based on received patientId
// ...
return View(model);
}

What is wrong with my codes for passing Form Data and Listbox data to controller by ajax?

Can anybody help me to find what is wrong with my codes for passing form data and Listbox data to controller by ajax?
Here is the ajax code:
$("#btnGetData").click(function () {
var button1 = "getdata";
var listItms = $('#ChooseRight').val(); // this is Lisbox field in Razor view
var formData = $('#GenForm').serialize(); //the Form ID of razor view
var wildcardprodtype = $('#WildCardProdType').val();
$.ajax({
type: 'POST',
url: '/Report/LongRunningProcess', //controller name
data: JSON.stringify({
button: button1,
viewModel: formData,
ChooseRight: listItms,
WildCardProdType: wildcardprodtype
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
}
});
Here is the controller, in debug, I can see the data of "button", WildCardProdType are passed properly, but not the data of viewModel and ChooseRight list. Any reason why?
public ActionResult LongRunningProcess(string button, ReportViewModel viewModel, List<string> ChooseRight, string WildCardProdType)
{
....
here is the #HtmlBegin form header:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "GenForm" } ))
{
By the way, the current razor view use ReportViewModel as this:
#model MVCPROD.Models.ViewModels.ReportViewModel
Use serializeArray() instead serialize() so that you can include more items in the form serialized array.
$("#btnGetData").click(function () {
var button1 = "getdata";
var listItms = $('#ChooseRight').val();
var wildcardprodtype = $('#WildCardProdType').val();
var formData = $('#GenForm').serializeArray();
//Below three lines are not required if ChooseRight, WildCardProdType elements are inside the form
formData.push({ name: 'button', value: button1 });
formData.push({ name: 'listItms', value: listItms });
formData.push({ name: 'wildcardprodtype', wildcardprodtype });
$.post(
'/Account/LongRunningProcess',
formData,
function (response) {
}
);
});

checking if the success data is empty in ajax method of jquery

I have two select boxes in my form.when a user select an option of first select box the options of second select box will be shown by jquery ajax.My problem is that some options of first select box has no record in database and when they selected the second select box should not be shown.I need to check if the data is empty .I treid this code but nothing happens
view:
<script type='text/javascript'>
$(document).ready(function(){
$('#subsec').hide();
$('section').change(){
var sec_id=$(this).val();
var url='article_controler/get_options/'+sec_id;
$.ajax({
url:url,
type:'post',
success:function(resp){
if(!resp)
$('#subsec').hide();
else
$('#subsec').show();
$('$subsec').html(resp)
})
}
});
</script>
you can try this
$.ajax({
url:url,
type:'post',
success:function(resp){
if(resp == "" || resp == null){
$('#subsec').hide();
}
else {
$('#subsec').show();
$('#subsec').html(resp);
}
})
}
});
I have added inline comments to help you out
class Article_Controller extends CI_Controller
{
public function get_options()
{
$option = $this->input->post('option'); // validate this
//Get a list of Sub options from your model
$model = ''; //your own implementation here
//If no model data returned, send a 404 status header
//and bail
if(!$model){
return $this->output->set_status_header(404);
}
$responce = array(
'suboptions' => $model // array of suboptions the model returned
);
// Ideally Abstract all the Ajax stuff to
// its own controller to keep things Dry
return $this->output
->set_status_header(200)
->set_content_type('application/json')
->set_output(json_encode($responce));
}
}
-
//Global URL variable or put it in <base href>
var URL = "<?php echo site_url();?>";
(function($){
var myForm = {
init : function(){
//initialize myForm object properties here
this.Form = $("form#myFormID");
this.selectChange = this.Form.find("select#mySelectBoxI");
this.newSelect = this.Form.find("select#secondaryselectboxId");
//hide second select with CSS by default
//Bind the Change event to our object(myForm) method
this.selectChange.on('change', $.proxy(this.ChangedEvent, this));
},
ChangedEvent : function(event){ // gets the change event
//Grab the currentTarget(option[i]) value from the event received
//You may also need to pass the CSRF Token
this.buildAjaxRequest({'option' : event.currentTarget.value});
},
buildAjaxRequest : function( data ){
var config = {
cache : false,
url : URL + 'article_controller/get_options',
method : 'POST',
data : data, //'option' : event.currentTarget.value
dataType : 'json'
};
this.makeAjaxRequest(config).then(
$.proxy(this.ResponceHandler, this),
$.proxy(this.ErrorHandler, this)
);
},
makeAjaxRequest : function( config ){
return $.ajax( config ).promise();
},
ResponceHandler : function( data ){
$.each(data.suboptions, function(i, v){
this.newSelect.append('<option value="'.data[i].'">'.data[v].'</option>');');
});
this.newSelect.show();
},
ErrorHandler : function(xhr, statusText, exception){
switch(xhr.status)
{
case 404: //remember the 404 from the controller
alert(xhr.statusText); //handle your own way here
break;
}
},
}
myForm.init();
}(jQuery));
Hi pls try this,
<script type='text/javascript'>
$(document).ready(function(){
$('#subsec').hide();
$('#firstSelectBoxId').change("selectboxMethod");
});
function selectboxMethod(){
var sec_id=$("#firstSelectBoxId").val();
alert("Selected from first select"+sec_id);
if(sec_id != null){
var url='article_controler/get_options/'+sec_id;
$.ajax({
url:url,
type:'post',
success:function(resp){
$('#subsec').show();
$('#subsec').html(resp);
}
});
}else{
$("#subsec").hide();
}
}
</script>

$.submit form and replace div using ajax has strange jquery behaviour on the new partialview

I think the problem is with jQuery, i don't know for sure.
Let me explain the situation.
Screenshot 1
I fill in the partialView and click on submit.
The submit is a jQuery event handler with the following code:
_CreateOrEdit.cshtml
<script type="text/javascript">
$(document).ready(function () {
$('input[type=text], input[type=password], input[type=url], input[type=email], input[type=number], textarea', '.form').iTextClear();
$("input:checkbox,input:radio,select,input:file").uniform();
$("input[type=date]").dateinput();
});
$(window).bind('drilldown', function () {
$(".tabs > ul").tabs("section > section");
});
$("#CreateOrEditSubmit").submit(function () {
//get the form
var f = $("#CreateOrEditSubmit");
//get the action
var action = f.attr("action");
//get the serialized data
var serializedForm = f.serialize();
$.post(action, serializedForm, function (data) {
$("#main-content").html(data);
});
return false;
});
</script>
This all works fine on the first-run.
Then when i submit the form when it is invalid (Screenshot 1),
[HttpPost]
public ActionResult Create(Client client)
{
if (ModelState.IsValid)
{
context.Clients.Add(client);
context.SaveChanges();
return RedirectToAction("Index");
}
return PartialView(client);
}
Then it tries to redisplay the same form again (Controller Client, Action Create), but something isn't triggered right (Screenshot 2). The layout is wrong (buttons still hidden), the tabs aren't working (javascript), ...
Worst of all, i don't get any error in Firebug, Chrome Console, ...
Does anyone have an idea what could be the problem, because i really haven't got a clue what's happening. It seems to me that nothing has changed, but it did :s
Fyi, an equivalant for the post function is :
var request = $.ajax({
type: 'POST',
url: action,
data: serializedForm,
success: function (data) {
$("#main-content").html(data);
},
dataType: 'HTML'
});
request.done(function (msg) {
$("#log").html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
Before submit, everything loads fine
After submit, same form is called. jQuery isn't working anymore and form is getting bricked (i think this is "side" behaviour from the jQuery breaking)
Edit: (on request)
Here is the partialView in full
_CreateOrEdit.cshtml doesn't contain any javascript for now, the result is the same, so i only posted Create.cshtml.
Create.shtml
#model BillingSoftwareOnline.Domain.Entities.Client
<div class="container_12 clearfix leading">
<div class="grid_12">
#using (Html.BeginForm("Create", "Client", FormMethod.Post, new { #class="form has-validation", id="CreateOrEditSubmit"}))
{
#Html.Partial("_CreateOrEdit", Model)
<div class="form-action clearfix">
<button class="button" type="submit">
OK</button>
<button class="button" type="reset">
Reset</button>
</div>
}
</div>
</div>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.itextclear.js")"> </script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.uniform.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.tools.min.js")"> </script>
<script type="text/javascript">
$(document).ready(function () {
$('input[type=text], input[type=password], input[type=url], input[type=email], input[type=number], textarea', '.form').iTextClear();
$("input:checkbox,input:radio,select,input:file").uniform();
$("input[type=date]").dateinput();
});
$(window).bind('drilldown', function () {
$(".tabs > ul").tabs("section > section");
});
$("#CreateOrEditSubmit").submit(function () {
//get the form
var f = $("#CreateOrEditSubmit");
//get the action
var action = f.attr("action");
//get the serialized data
var serializedForm = f.serialize();
// $.post(action, serializedForm, function (data) {
// $("#main-content").html(data);
// });
var request = $.ajax({
type: 'POST',
url: action,
data: serializedForm,
success: function (data) {
$("#main-content").html(data);
},
dataType: 'HTML'
});
return false;
request.done(function (msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
</script>
Since this markup is returned as a partial, you need to reinitialize your javascript.
This is hacky, but try putting your script in the partial view, instead of _CreateOrEdit.cshtml, and see if that works.
Update
After seeing the cshtml, it looks like it is not working because $(document).ready() has already executed, before the ajax load. Try this instead:
$(function () {
$('input[type=text], input[type=password], input[type=url], input[type=email], input[type=number], textarea', '.form').iTextClear();
$("input:checkbox,input:radio,select,input:file").uniform();
$("input[type=date]").dateinput();
$(window).bind('drilldown', function () {
$(".tabs > ul").tabs("section > section");
});
$("#CreateOrEditSubmit").submit(function () {
//get the form
var f = $("#CreateOrEditSubmit");
//get the action
var action = f.attr("action");
//get the serialized data
var serializedForm = f.serialize();
// $.post(action, serializedForm, function (data) {
// $("#main-content").html(data);
// });
var request = $.ajax({
type: 'POST',
url: action,
data: serializedForm,
success: function (data) {
$("#main-content").html(data);
},
dataType: 'HTML'
});
return false;
request.done(function (msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
});
Add the following instructions to the end of your ajax callback, so that the styling is applied after the form has been injected to the DOM:
$('input[type=text], input[type=password], input[type=url], input[type=email], input[type=number], textarea', '.form').iTextClear();
$("input:checkbox,input:radio,select,input:file").uniform();
$("input[type=date]").dateinput();
$(".tabs > ul").tabs("section > section");

How to Update TextBox in MVC Ajax

How do i update textbox using MVC Ajax UpdateTargetId option.?
I am new to MVC Ajax applications. Please any one help me out.
Thanks,
Pon Kumar Pandian .T
you can achieve that simple concept using
1- Post\Get
2- Ajax
Note: just replace the $("#myform").html() with $("#mytext").text = "data"
1- Using Get\Post
/////// Controller post and get simple text value
[HttpPost]
public string Contact(string message)
{
return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";
}
//// in the view add reference to the Javascript (jQuery) files
#section Scripts{
<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.intellisense.js"></script>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
}
/// then add the Post method as following:
<script type="text/javascript">
/// post and get text value
$("#send").on("click", function () {
$.post('', { message: $('#msg').val() })
//// empty post('') means post to the default controller,
///we are not pacifying different action or controller
/// however we can define a url as following:
/// var url = "#(Url.Action("GetDataAction", "GetDataController"))"
.done(function (response) {
$("#myform").html(response);
})
.error(function () { alert('Error') })
.success(function () { alert('OK') })
return false;
});
</script>
2-Also you can use Get only as following:
/////Controller = Home
//// Action = FullName
///// get only simple text message
[HttpGet]
public string FullName()
{
return "full Name: Mahmoud Sayed";
}
/// in the view:
$("#getfullname").on("click", function () {
var url = "#(Url.Action("FullName", "Home"))"
$.get(url, { })
.done(function (response) {
$("#myform").html(response)
})
.error(function () { alert('Error') })
.success(function () { alert('OK') })
return false;
});
</script>
3- Now let's say you want to do it using $.Ajax and JSON:
// Post JSON data add using System.Net;
[HttpPost]
public JsonResult JsonFullName(string fname, string lastname)
{
var data = "{ \"fname\" : \"" + fname + " \" , \"lastname\" : \"" + lastname + "\" }";
//// you have to add the JsonRequestBehavior.AllowGet
//// otherwise it will throw an exception on run-time.
return Json(data, JsonRequestBehavior.AllowGet);
}
Then, inside your view: add the event click on a an input of type button, or even a from submit:
Just make sure your JSON data is well formatted.
$("#jsonGetfullname").on("click", function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "#(Url.Action("JsonFullName", "Home"))",
data: "{ \"fname\" : \"Mahmoud\" , \"lastname\" : \"Sayed\" }",
dataType: "json",
success: function (data) {
var res = $.parseJSON(data);
$("#myform").html("<h3>Json data: <h3>" + res.fname + ", " + res.lastname)
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
})
});
</script>
cheers,
Mahmoud Sayed
You can simply wrap all you want to update in some div with id same that you're putting in UpdateTargetId property, and return new content(new textbox with new value). And also don't forget to set Ajax updating type to replace(not append).
We can't give the textbox control id directly in UpdateTargetId property. Bur we can do work around to achieve this. Please fine the blow mention code for the same.
//This the call back method once the ajax request has been successes.
function fnOnSuccess(context) {
alert(context); //this context having all the current ajax req & res information.
var response = context.get_data(); //Using this get_data() method we can get the response from server.
$('#txtajaxResponse')[0].value = response;
}
<!-- Code in .aspx page -->
<%=Ajax.ActionLink("TextBox in UpdateTargetId","GetInfo","Ajax",new AjaxOptions{OnSuccess = "fnOnSuccess"}) %>
<%=Html.TextBox("txtajaxResponse")%>
Thanks,
Pon Kumar Pandian .T

Resources