I am trying to get the data of a hidden textbox from the index to a textfield in another view.
First, I get the data using AJAX.
//ajax
if (id && toolcode && shopdoccode) {
$.ajax({
type: 'GET',
url: '#Url.Action("delivery", "service")',
data: { id, memo },
success: function (data) {
if (data.success) {
console.log("Succes");
window.location.href = '#Url.Action("delivery", "service")';
}
},
error: function (data) {
console.log("Error");
}
});
}
window.location.href = ("service/delivery?id=" + id + "&toolcode=" + toolcode + "®date=" + regdate + "&shopdoccode=" + shopdoccode + "&memo" + memo);
}
Then, I make a viewbag in the controller to pass the data to my other view.
public ActionResult Delivery(string id, string memo)
{
ServiceOrder service = GetService(id);
ViewBag.id = id;
ViewBag.memo = memo;
And finally, in the view
#using (Html.BeginForm("GeneratePDF", "Service", FormMethod.Post, new { #class = "form-style-4", id = "getPDFForm" }))
{
string memofield = ViewBag.memo;
//code
<textarea name="jobdescription" readonly>#memofield</textarea>
if I set breakpoints in the controller, I can see that Viewbag.memo contains the correct data. Once in the view I've set a breakpoint on the string memofield = viewbag.memo
Even there, I can see the data. but then, suddenly, if I press continue, the strings are back to 'null'
What am I missing here?
It can happen because after you send ajax request you are redirecting back to Delivery action window.location which does not contain post parameters id and memo.. see
success: function (data) {
if (data.success) {
console.log("Succes");
window.location.href = '#Url.Action("delivery", "service")';
}
}
Related
I have an ajax call (GET) to a controller action to generate and return a url (JSON). When I run the code the ajax call goes but it never hits the controller action. I get a 500 error with no response text. I'm stumped. Below is my code, Thanks!
[HttpGet]
public ActionResult ViewOrderForm(int? id)
{
if (id == null || id == 0)
{
_logger.LogInformation("Order Id " + id + " does not exisit in the database. User is unable to view form.");
return NotFound("Order Id " + id + " does not exisit in the database.");
}
return Json(new
{
newUrl = Url.Action("ViewOrder", new { id = id })
}
);
}
function viewOrderForm(id) {
$.ajax({
url: siteURLS.ViewOrderForm,
method: "GET",
data: {
id: id
},
error: function (e) {
alert("Unable to open ITO form. " + e.responseText);
}
}).done(function (data) {
//alert(data.newUrl);
window.location.replace(data.newUrl);
});
}
Believe its type instead of method in ajax property
try this ajax,
$.ajax(
{
url: siteURLS.ViewOrderForm+"?id="+id,
type: 'GET',
dataType: 'json',
success: function (data) {
window.location.replace(data.newUrl);
},
error: function (e) {
alert("Unable to open ITO form. " + e.responseText);
}
});
I have a DropDownList in my View and I want to capture the ID of the selected value from both the DropDownList and pass that value as an argument in one of my Controller action method.
#Html.DropDownList("ddlL", new SelectList(string.Empty, "Value", "Text"), "Select")
<script type="text/javascript">
$("#ddlL").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("LoadLDet")',
datatype: 'JSON',
success: function (data) {
$("#ddlL").append('<option value=' + '0' + '>' + 'Select' + '</option>');
$.each(data, function (key, value) {
$("#ddlL").append('<option value=' + value.LId + '>' + value.LName + '</option>');
});
},
error: function (ex) {
alert('Failed to display Data');
}
});
$("#ddlL").change(function () {
$("#ddlW").empty();
var LID=$(this).val();
alert(LID);
$.ajax({
type: 'POST',
url: '#Url.Action("GetWTest")',
datatype: 'JSON',
data: { LocID: $("#ddlL").val() },
success: function (data) {
$("#ddlW").append('<option value=' + '0' + '>' + 'Select' + '</option>');
$.each(data, function (key, value) {
$("#ddlW").append('<option value=' + value.WinId + '>' + value.WinName + '</option>');
});
},
error: function (ex) {
alert('Failed to load Win data');
}
});
return false;
});
</script>
Here With the help of LoadLDet() I am getting all the data and binding it in first DropDownList ddlL. And then passing the LocID getting from Change Event function of DropDownList ddlL to JsonResult GetWin() to bind the data of second DropDownList ddlW.
[HttpPost]
public JsonResult LoadLDet()
{
MyService.ServiceInfoClient Service = new MyService.ServiceInfoClient();
var Loc = Service.GetLocList();
return Json(Loc);
}
public JsonResult GetWin(string LocID)
{
MyService.ServiceInfoClient Obj = new MyService.ServiceInfoClient();
IEnumerable<MyService.Win> Win = Obj.GetWinByLocId(Convert.ToInt32(LocID));
return Json(Win);
}
I have another ActionResult ExportDataInExcel() class in which I want to pass selected DropDownList items LId and WId as argument in one of the method which I am calling to get data which needs to be exported. Please guide me how I can pass "LId" from view to controller which I am capturing in the Ajax also how can I pass WId i.e. the second DropDownList ID from View to below mentioned Action Method.
public ActionResult ExportDataInExcel()
{
ExportData(LId, WId, xyz);
return View("Index");
}
Take a look at this code. I used data to list all of the parameters that I want to send to server. I modified your code. I used getJSON method to fetch the JSON from the server. It's a little bit simpler.
<script type="text/javascript">
$("#ddlL").empty();
// Get data from LoadLDet action.
$.getJSON('#Url.Action("LoadLDet")', function(data) {
$("#ddlL").append('<option value="0">Select</option>');
$.each(data, function (key, value) {
$("#ddlL").append('<option value=' + value.LId + '>' + value.LName + '</option>');
});
});
// Send data to ExportDataInExcel action.
$("#ddlL").on('change', function() {
var lId = $(this).val();
var wId = $("#otherDropdownId").val();
$.ajax({
type: 'POST',
url: '#Url.Action("ExportDataInExcel")',
datatype: 'json',
data: {
LId: lId, // FIRST DROPDOWN VALUE
WId: wId // SECOND DROPDOWN VALUE
},
success: function (data) {
alert("Data successfuly sent.");
},
error: function () {
alert("Error occured while sending the data.");
}
});
});
</script>
Your action that receives parameter.
public ActionResult ExportDataInExcel(int LId, int WId)
{
ExportData(LId, WId, xyz);
return View("Index");
}
this can help
$("#ddlL").on('change', function() {
var id =$(this).val(); // here's your value
alert(id); // show your value
// do your ajax call here
});
I have a method where my users can change their password,to a new one,requiring 2 variables,one is the new password,and the other,the repetition of the password.The thing is that when i call the method, it returns the string "undefined",and uses that string as the new password,saving it on the db.
Can someone tell me what I'm doing wrong?
Controller:
[HttpPost]
public JsonResult ChangePwdEnt(string pwd, string repeatpwd)
{
if (pwd == null || repeatpwd == null)
{
ViewBag.Error = "Insira os campos obrigatórios";
}
else
{
if (pwd == repeatpwd)
{
changePwd_Entidades(Session["ID"].ToString(),pwd);
return Json(true,JsonRequestBehavior.DenyGet);
}
else
{
ViewBag.Error = "As palavras chave precisam de ser iguais";
}
}
return Json(false, JsonRequestBehavior.DenyGet);
}
Script:
<script>
$('.alt-btn').on('click', function () {
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("ChangePwdEnt", "Home")?pwd=' +
$('#Info_pwd').val() + '&repeatpwd=' + $('#Info_repeatpwd').val(),
error: function (e) {
console.log(e);
},
success: function (Changed) {
if (Changed) {
window.location = "Entidades";
} else if (!Changed) {
window.location = "LoginEntidades";
}
}
});
});
I think you are using incorrect id to get value of password field.
And instead of sending both password to code better approach would be just compare your both password values at client side and if they both are same then parse those values to code side other wise ask user to input same password .
That would be better to Send the data in the data parameter while you're using POST method
var data = JSON.stringify({
'pwd': $('#Info_pwd').val(),
'repeatpwd':$('#Info_repeatpwd').val()
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("ChangePwdEnt", "Home"),
data: data,
error: function (e) {
console.log(e);
},
success: function (Changed) {
if (Changed) {
window.location = "Entidades";
} else if (!Changed) {
window.location = "LoginEntidades";
}
}
});
This is for using POST method. If you want to use GET method than it would be fine to pass data in query string.
I' m new to MVC and was trying out some things but I can' t get this to work.
I have this script that should insert a partial view inside the page based on the dropdownlist selection.
$(function () {
$('#ddTipologiaFattura').change(function () {
var selectedID = $(this).val();
$.ajax({
url: '/Admin/Fatturazione/GetPartial/' + selectedID,
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html'
})
.success(function (result) {
$('#partialPlaceHolder').html(result);
})
.error(function (xhr, status, error) {
alert(status + '\n' + error)
});
});
});
This is my controller ~/Areas/Admin/Controllers/FatturazioneController.cs
[RouteArea("Admin")]
[Route("Fatturazione/{action}")]
public class FatturazioneController : Controller
{
private MyEntity db = new MyEntity();
public ActionResult GetPartial(int partialViewId)
{
if (partialViewId == 0)
{
var fatturaAziendaVM = new FatturaPerAziendaViewModel();
ViewBag.Intestatario = new SelectList(db.Azienda, "AziendaNome", "AziendaNome");
return PartialView("~/Areas/Admin/Views/Fatturazione/_ListaAziende.cshtml", fatturaAziendaVM);
}
var fatturaVM = new FatturaViewModel();
return PartialView("~/Areas/Admin/Views/Fatturazione/_Intestatario.cshtml", fatturaVM);
}
I keep getting a Not Found error by the script.
What am i doing wrong?
Your route only accounts for the action, not for the Id, which is why it's failing. You should either update the route per action to account for the Id, or append the id as a query string parameter.
$.ajax({
url: '/Admin/Fatturazione/GetPartial?partialViewId=' + selectedID,
I am trying to call an ActionResult and update the value of an img on the page based on the returned result from the Action, but for some reason I post to a new page that just prints the string
public ActionResult Favorite(int? id)
{
int PId = Convert.ToInt32(pid);
if (MyDb.CheckExist(Convert.ToInt32(User.Identity.Name),PId))
{
var UF = MyDb.GetExist( Convert.ToInt32(User.Identity.Name),PId);
MyDb.Delete(UF);
MyDb.Save();
return Json(new { Url= "/Content/oldimage.png" }, JsonRequestBehavior.AllowGet);
}
else
{
UFs UF = new UFs();
UF.Id = PId;
UF.UserId = Convert.ToInt32(User.Identity.Name);
UF.CreatedDate = DateTime.Now;
MyDb.Add(UF);
MyDb.Save();
return Json(new { Url= "/Content/newimage.png"}, JsonRequestBehavior.AllowGet);//return favorite image
}
}
my anchor tag that calls my ajax
<a href='<%= Url.Action("Favorite","Home", new { id = item.Id })%>' class="Image" style="text-decoration:none">
<img src="/Content/Images/oldimage.png" alt="FavoriteImage" style="height:25px;width:30px" id="favorite<%:item.Id %>" class="ImageTag" /></a>
$('.Image').click(function () {
var id = this.children('.ImageTag').attr('id');
$.ajax({
url: this.href,
type: 'POST',
dataType: "json",
success: function (data) {
$('#' + id).attr('src', data.Url);
},
error: function (xhr, ajaxOptions, thrownError) {
$.unblockUI();
}
});
return false;
});
and what happens is the action on the server is hit but the page posts to Home/Favorite displaying the returned Json. Home/Favorite is not even a view.
You should prevent the default behavior, the link is making a new request for the Favorite Action refreshing the whole page, getting as response the JSON.
$('.Image').click(function(event) {
event.preventDefault();
//do stuff here
});