Jquery Post two Array AngularJS - javascript

Im trying to send two Arrays on my AngularJS app but i get "404 URL Not Found". Is this ok? What am i missing?
My AngularJS code:
$scope.Guardar = function () {
if (confirm('¿Está seguro de guardar los datos?')) {
$("#btnGuardar").prop('disabled', 'disabled');
$scope.MostrarMensajeOk = false;
$scope.MostrarMensajeError = false;
var nombreRegla = $("#lblNombreRegla").val();
var localesEnGrilla = $("#localesGrilla").val();//array1
var articulosEnGrilla = $("#articulosGrilla").val();//array2
$http({
method: 'POST',
url: baseURL + 'Configuracion/CrearRegla/',
data: { "Nombre": nombreRegla, "Locales": localesEnGrilla, "Articulos": articulosEnGrilla, "CurrentUser": userName }
}).success(function (result) {
if (result != null) {
$("#btnGuardar").prop('disabled', '');
$scope.MostrarMensajeOk = false;
$scope.MostrarMensajeError = false;
$scope.volver();
}
});
};
};
And my Controller :
public void CrearRegla(string Nombre, string Locales, string Articulos, string CurrentUser)
{
//staff
}
The error that give me is "404 not found URL"

"404 URL Not Found" means that's url not valid.
Make sure that's baseURL end with / and for 'Configuracion/CrearRegla/' try without / like this 'Configuracion/CrearRegla'

Related

window.location.replace is always undefined

I have a ajax post that I need to redirect to redirect url on success.
In the browser debugger I do c the correct url but I'm always getting "MYURL/undefined".
$.ajax({
type: 'POST',
url: "/NewsLetter/Create",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: data,
success: function(result) { //debug >result={urlOne:'https://localhost:7077'}
// alert('Successfully received Data ');
if (result.UrlOne !== undefined) {
window.location.replace(result.UrlOne);
} else {
window.location.replace(result.UrlTwo);
}
console.log(result);
},
error: function(error) {
alert('Failed to receive the Data');
console.log(JSON.stringify(error));
console.log('Failed ');
}
});
In my controller:
if (ModelState.IsValid && isNewUser == null)
{
//remove for clear code
return Json(new { UrlOne = Url.ActionLink("Index","Home")});
}
TempData["ErrorMes"] = "You are allready register";
return Json(new { UrlTwo = Url.ActionLink("_RegNews", "NewsLetter") });
Pass the JsonSerializerOptions as a parameter when creating the Json object to make property's name case-sensitive during deserialization. The JsonSerializerOptions has PropertyNameCaseInsensitive property that by default set to false. This will prevent the Json serializer to change names to be camel-cased.
var options = new System.Text.Json.JsonSerializerOptions();
if (ModelState.IsValid && isNewUser == null)
{
//remove for clear code
return Json(new { UrlOne = Url.ActionLink("Index","Home")}, options);
}
TempData["ErrorMes"] = "You are allready register";
return Json(new { UrlTwo = Url.ActionLink("_RegNews", "NewsLetter") }, options);
JsonSerializerOptions Class
Please check the return json from controller:
You will find that the key is urlOne instead of UrlOne.
Javascript is case sensitive, So you need to change your code like:
if (result.urlOne !== undefined) {
window.location.replace(result.urlOne);
} else {
window.location.replace(result.urlTwo);
}

Saving changes to the DB MVC

I have a problem when I try to save some data to the database. I can see the ID and Date returning me appropriate values in the JS function... However, the parameter for the Process function inside the controller class remains null. I don't know why is that happening. There is a linq query that is also included in the Hello Model, but I didn't include it because there is no need for it.
Model:
public class Hello
{
List<string> Ids { get; set; }
List<string> Dates { get; set; }
}
Controller:
[HttpPost]
public ActionResult Process(string ids, string dates)
{
Hello model = new Hello();
if (ModelState.IsValid)
{
using (db = new DB())
{
rp = new RequestProcess();
//var c = rp.getHello(model, dates);
var c = rp.getStuff();
if (c != null)
{
foreach (var i in c)
{
if (i != null)
{
ids = i.ID;
dates = i.Date.ToString();
}
db.SaveChanges();
}
}
}
ViewBag.Message = "Success";
return View(model);
}
else
{
ViewBag.Message = "Failed";
return View(model);
}
}
View:
<td><input class="id" type="checkbox" id=#item.ID /></td>
<td>#Html.DisplayFor(x => #item.ID)</td>
<td><input class="date" id=date#item.ID type="text" value='#item.Date'/></td>
$(document).ready(function () {
var ids = "";
var dates = "";
$("#btnSubmit").bind("click", function () {
createUpdateArrays();
var url = "/Sample/Process";
$.ajax({
type: "POST",
url: url,
data: { ids: ids, dates: dates },
contentType: 'application/json; charset=utf-8',
success: function (success) {
if (success === true) {
alert("HERE WE ARE");
}
else {
alert("eror");
}
}
});
ids = "";
dates = "";
});
function createUpdateArrays() {
var i = 0;
$('input.remedy-id:checkbox').each(function () {
if ($(this).is(':checked')) {
var rid = $(this).attr("id");
$('.planned-date').each(function () {
var did = $(this).attr("id");
if (did === rid) {
var date = $(this).val();
ids += rid + ",";
dates += date + ",";
}
});
};
});
};
Any help would be appreciated!
I think you need contentType: 'application/json' in your $.ajax({});
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json'
});
Also, try adding [FromBody]Hello model in your controller action.
There are several issues in your code:
1) You're passing JSON string containing viewmodel properties, it is necessary to set contentType: 'application/json; charset=utf-8' option in AJAX callback to ensure model binder recognize it as viewmodel parameter.
2) return View() is not applicable for AJAX response, use return PartialView() instead and put html() to render response in target element.
Therefore, you should use AJAX setup as provided below:
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('#targetElement').html(result);
},
error: function (xhr, status, err) {
// error handling
}
});
Controller Action
[HttpPost]
public ActionResult Process(Hello model)
{
if (ModelState.IsValid)
{
using (db = new DB())
{
// save data
}
ViewBag.Message = "Success";
return PartialView("_PartialViewName", model);
}
else
{
ViewBag.Message = "Failed";
return PartialView("_PartialViewName", model);
}
}
Remember that AJAX callback intended to update certain HTML element without reloading entire view page. If you want to reload the page with submitted results, use normal form submit instead (with Html.BeginForm()).

ASP.NET MVC POST Route does not point to the correct Method

I´ve got a problem with my current mvc project.
I´m using an ajax call to send new comments to the server but the method does not even get called.
My js code:
$("#answer_button").click(function () {
showLoadingTab();
var actionUrl = '#Url.Action("AnswerThread", "Threads")';
var threadId = $("#threadId").val();
var msg = $("#answer_msg").val();
alert(actionUrl);
alert(msg);
alert(threadId);
$.ajax({
url: actionUrl,
type: "POST",
data: "Message=" + msg + "&threadId=" + threadId,
success: function (msg) {
hideLoadingTab();
location.reload();
},
error: function () {
alert("Ein Fehler ist aufgetreten.");
hideLoadingTab();
}
});
});
as you see I´ve alerted the url, msg and threadId and they are all correct. url: "/Threads/AnswerThread", msg: "test", threadId: 1.
I´ve already tried to put a breakpoint inside the AnswerThread method but it does not get called. The "AnswerThread" method is inside the "ThreadsController" and looks like this:
[HttpPost]
public ActionResult AnswerThread(string Message, int threadId)
{
var userId = User.Identity.GetUserId();
using (var db = new UnitOfWork(new BlogContext()))
{
db.Posts.Add(new Post()
{
Message = Message,
PublishTime = DateTime.Now,
ThreadId = threadId,
UserId = userId
});
db.Complete();
}
return PartialView("/Views/Partial/Clear.cshtml");
}
That´s exactly the same way I did it in the backend controllers but there it just works fine.
I hope somebody can help me..
UPDATE:
Made some changes just to try if any other way works.
Change1 js:
var data = {
threadId: threadId,
Message: msg
};
$.ajax({
url: actionUrl,
type: "POST",
content: "application/json; charset=utf-8",
dataType: "json",
data: data,
success: function (msg) {
if (msg.success == true) {
hideLoadingTab();
location.reload();
}
else
{
alert("Ein Fehler ist aufgetreten: " + msg.error);
}
},
error: function () {
alert("Ein Fehler ist aufgetreten.");
hideLoadingTab();
}
});
Change 2 c#:
[HttpPost]
public JsonResult AnswerThread([System.Web.Http.FromBody]PostDataModel data)
{
var userId = User.Identity.GetUserId();
string error = "";
bool success = false;
try
{
using (var db = new UnitOfWork(new BlogContext()))
{
db.Posts.Add(new Post()
{
Message = data.Message,
PublishTime = DateTime.Now,
ThreadId = data.threadId,
UserId = userId
});
success = true;
db.Complete();
}
}
catch(Exception ex)
{
error = ex.Message;
}
return Json(String.Format("'Success':'{0}', 'Error':'{1}'", success, error));
I tried this now with and without the "[FromBody]" statement.
Oh yes and I´ve added the DataModel like this:
public class PostDataModel
{
public int threadId { get; set; }
public string Message { get; set; }
}
and I also tried to manually configure the pointed route.
routes.MapRoute(
name: "AnswerThread",
url: "threads/answer",
defaults: new { controller = "Threads", action = "AnswerThread" }
);
The "actionUrl" variable in js get´s changed to /threads/answer but I´m always getting 500 Internal Server Error. When I put a breakpoint inside the method it does not stop at any point of the ajax call.
In the Chrome Dev Tools at the "Network" tab it says to me that there is a parameter called "id" which is null which causes to this 500 internal server error. I tried to find out more information about this but the error does not tell me where this parameter is located.
I´ve got no parameter called "id" inside this method or the data model so where does this come from?
Solution:
My Routes mapping was bad. I first mapped the route /threads/{id} and THEN did /threads/answer so when the /threads/answer got called it thought "answer" is an id so it tried to enter the "Index" method. So for my particular problem (and maybe for some other guys having the same issue) the solution was just to put the mapping of the /threads/answer route in front of the /threads/{id} route and it worked.
Please check your parameter types, in controller threadId is int type and from ajax call you are passing string type.
In Js
$("#answer_button").click(function () {
showLoadingTab();
var actionUrl = '#Url.Action("AnswerThread", "Home")';
var threadId = parseInt($("#threadId").val());
var msg = "Answer message";
alert(threadId);
$.ajax({
url: actionUrl,
type: "POST",
data: { Message: msg, threadId: threadId },
success: function (msg) {
hideLoadingTab();
location.reload();
},
error: function () {
alert("Ein Fehler ist aufgetreten.");
hideLoadingTab();
}
});
});
In Controller
[HttpPost]
public ActionResult AnswerThread(string Message, int threadId)
{
return Json("Data");
}

MVC Post Uploaded File and model to controller [duplicate]

This question already has answers here:
How to append whole set of model to formdata and obtain it in MVC
(4 answers)
Closed 7 years ago.
I need post a uploades file and model, i use mvc this the code in the view:
function GuardarDocumento() {
var fileUpload;
var tipoDoc;
if (currentTabTitle == "#tab-AT") {
fileUpload = $("#inputFileAT").get(0);
tipoDoc = 'A';
}
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
var documento = {
Id_emd: 0,
Id_emm: {
Id_emm: id,
Tipo: tipo,
},
Tipo_emd: tipoDoc,
Fecha_emd: $("#txtFechaDocAT").val(),
Nombre_emd: $("#txtNombreDocAT").val(),
}
$.ajax({
url: "/Empleado/GuardarDocumento/" + JSON.stringify(documento),
type: "POST",
data: data,
contentType: false,
processData: false,
success: function (data) {
if (data.success) {
alert("Documento Guardado con Éxito.");
Cancelar();
}
else {
alert(data.message);
}
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
And the controller code:
[HttpPost]
public ActionResult GuardarDocumento(clsDocumentoEmpleadoModel documento)
{
try
{
if (Request.Files.Count > 0)
{
clsEmpleadoBLL bll = new clsEmpleadoBLL();
bll.PostedFile = Request.Files[0];
documento.Archivo_emd = Request.Files[0].FileName;
bll.AddDocument(documento);
}
else
{
return Json(new { success = false, message = "No ha seleccionado ningún archivo." });
}
}
catch (Exception ex)
{
GENException.Write(ex, "EmpleadoController.GuardarDocumento");
return Json(new { success = false, message = string.Format("Error: {0}", ex.Message) });
}
return Json(new { success = true, message = "Documento Guardado Correctamente." });
}
It does not work, bad request. If I put url: "/Empleado/GuardarDocumento/" + documento, i get into controller code but model is null.
What is wrong? I am trying send to controller both uploaded file and model, how can I do that?
The type that you're sending to the controller action must match the type the action is expecting. You're sending a FormData, and you're expecting a clsDocumentoEmpleadoModel.

Refresh Index after redirecting to it from AJAX call

I have a situation where I am setting a user value and trying to reload the index page. This is only a sample page and I cannot user any kind of user controls, like ASP.NET. Each user is in the database and the role is retrieved from there. My index is this:
[HttpGet]
public ActionResult Index(long? id)
{
AdminModel admin = new AdminModel();
UserModel usermodel = new UserModel();
if (id != null)
{
admin.UserModel = usermodel;
admin.UserModel.UserId = id.ToString();
admin.UserModel = UserAndRoleRepository.GetOrStoreUserProfile(admin.UserModel.UserId);
}
else
{
admin.UserModel = usermodel;
admin.UserModel = UserAndRoleRepository.GetOrStoreUserProfile(currentUser);
}
return View(admin);
}
This works fine when first loaded. In the page I am setting values based upon the user role:
$(document).ready(function () {
debugger;
user = function () { return #Html.Raw(Json.Encode(Model)) }();
if (user.UserModel != null) {
if (user.UserModel.UserRole == 'ADMIN') {
$("#btnAdmin").show();
$("#btnTran").show();
$("#btnNew").show();
$("#btnAdjust").show();
$("#btnReports").show();
}
if (user.UserModel.UserRole == 'TRANS') {
$("#btnReports").show();
$("#btnTran").show();
}
if (user.UserModel.UserRole == 'REPORTS') {
$("#btnReports").show();
}
}
});
The AJAX call is this:
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("SetUser")',
data: { userid: ui.item.value },
success: function (data) {
if (data == null) {
}
else {
}
},
error: function (xhr) {
//var err = xhr.responseText;
//alert('error');
}
});
And the SetUser action:
[HttpPost]
public ActionResult SetUser(string userid)
{
return RedirectToAction("Index", new { id = Convert.ToInt64(userid) });
}
This works fine in that the Index method is fired with the chosen ID, but the page does not reload to be able to set the buttons. Any ideas?
It won't redirect because you're returning an action via an ajax call. The best thing to do here would be to return the userid as JSON, then do the redirect.
So the ajax success function would be:
success: function (data) {
if (data != null && data.UserID != null) {
location.href = '#(Url.Action("SetUser"))?userid=' + data.UserID;
}
else {
location.reload(); //something went wrong?
}
},
});
And your action would be:
[HttpPost]
public JsonResult SetUser(string userid)
{
return Json(new { UserID = Convert.ToInt64(userid) });
}
Do you need to make Ajax POST call? If not you can replace that code with
window.location.href = '#Url.Action("Index")' + '/' + ui.item.value
or
window.location.href = '#Url.Action("Index")' + '?id=' + ui.item.value
depending on your route mapping.

Categories