The HTTP verb POST used to access path '/Documents/TestNote/Documents/AddNote' is not allowed - asp.net-mvc

I am having two user control on a aspx page and one of the user control has a text area for notes. and i am trying to use JSON so that when they click the addnote button it does not reload the page.
Below is my java script , but it says that it is giving this error
The HTTP verb POST used to access path '/Documents/TestNote/Documents/AddNote' is not allowed.
<script type="text/javascript">
$(document).ready(function() {
$("#btnAddNote").click(function() {
alert("knock knock");
var gnote = getNotes();
//var notes = $("#txtNote").val();
if (gnote == null) {
alert("Note is null");
return;
}
$.post("Documents/AddNote", gnote, function(data) {
var msg = data.Msg;
$("#resultMsg").html(msg);
});
});
});
function getNotes() {
alert("I am in getNotes function");
var notes = $("#txtNote").val();
if (notes == "")
alert("notes is empty");
return (notes == "") ? null : { Note: notes };
}
</script>
My controller
[HttpPost]
public ActionResult AddNote(AdNote note)
{
string msg = string.Format("Note {0} added", note.Note);
return Json(new AdNote { Note = msg });
}

in the controller use
return Json(new AdNote { Note = msg },sonRequestBehavior.AllowGet);

I see two errors:
- var msg = data.Msg; should be var msg = data.Note;
- Use <%=Url.Action("AddNote","Documents")%> instead of "Documents\AddNote"

Related

Return view use Ajax

I want to call a view using Ajax script:
In main view:
<script>
var onCommand = function (column, command, record, recordIndex, cellIndex) {
Ext.Msg.alert('record = ' + record.data.ID);
Ext.Ajax.request({
url: '/Details/',
method: 'GET',
params: {
id: record.data.ID
},
success: function (response) {
var result = (response.responseText);
if (result != "") {
modelName = result;
CreateLookUp(combo, id, false, true);
} else {
CreateLookUp(combo, id, true, false);
}
}
});
}
</script>
Controller:
// GET: Bob/Details/5
public ActionResult Details(String ID)
{
int id = Convert.ToInt32(ID);
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BobRepository bobRepository = new BobRepository();
Bob bob = bobRepository.GetBob(id);
if (bob == null)
{
return HttpNotFound();
}
return View(bob);
}
The function call of the controller is called, the turget view is not returned. What is the reason?
I am not sure what you are trying to do, I am assuming you are filling that view in some pop up modal, first you need to return partial view instead of view, i suggest checking if the request is ajax then return partial view else return view,
something like this
if(Request.IsAjaxRequest())
{return PartialView(bob);}
else
return View(bob);
in your js, parse the text to html, you can use jquery.htmlparse
success: function (response) {
var result = $.parseHTML(response);
//do what you want with your html

Passing String parameter Value Through angular Service parameter Value is Automatically Appends Some Special Character

Here's my Angular controller
//Save And Update
$scope.AddUpdateBusinessType = function() {
var businessType = {
Code: $scope.businessCode,
BusiType: $scope.businessType
};
var getBusinessTypeAction = $scope.BusinessTypeAction;
if (getBusinessTypeAction == "Update") {
businessType.BusinessTypeId = $scope.businessTypeId;
var getBusinessTypeData = businessTypeService.updateBusinessType(businessType);
getBusinessTypeData.then(function (msg) {
GetAllBusinessType();
$scope.ClearBusinessTypeForm();
alert("Record Updated Successful");
$scope.BusinessTypeAction = "";
$scope.divBusinessType = false;
}, function () {
alert('Error in Updating Record');
});
} else {
**// Save Section**
var getExistBusinessCode = businessTypeService.checkBusinessTypeCode(businessType.Code);
getExistBusinessCode.then(function (businessTypeCode) {
debugger;
if (businessTypeCode == true) {
alert('Business Type Code Already Exist');
} else {
debugger;
var getBusinessTypeData = businessTypeService.addBusinessType(businessType);
getBusinessTypeData.then(function (msg) {
GetAllBusinessType();
$scope.ClearBusinessTypeForm();
alert("Record Added Successful");
$scope.divBusinessType = false;
}, function () {
alert("Error Occured In Saving Data");
});
}
},function() {
alert('Error Occured While Checking Records');
});
}
}
In the above code Save Section I am trying to check if a value is exists in a database so I'm passing a string value to: checkBusinessTypeCode(businessType.Code) Service.When I Debug and See Value its Seems Normal.
Here's My Service:
//Check Business Code
this.checkBusinessTypeCode = function (businessTypeCode) {
debugger;
var response = $http({
method: "post",
url: "/BusinessType/CheckBusinessTypeDetailByCode",
params: {
businessTypeCode: JSON.stringify(businessTypeCode)
}
});
return response;
}
But when Passing To Controller string value I get some unexpected behavior.
two \\ always appear automatically
example
"\"stringvalue\""
I'm Still Having Above Problem
but as a quick solution i did code as follows
public bool _CheckBusinessTypeDetailByCode(string businessTypeCode)
{
string bisCode = businessTypeCode.Replace("\"", "");
bool isExist;
isExist = _IBusinessTypeRepository.IsExist(x => x.IsActive && !x.IsDelete && x.Code == bisCode);
return isExist;
}
I don't know is it bad practice or not , any way it is solved my problem.
Before did this modification
string businessTypeCode always gives value as
"\"somevalue\""

Posting form data from Partial view to controller using ajax

I have a jquery grid that has a list of Employee Records.To edit the records there is a link on each row.On click of that A jquery model popup opens and loads the partial view to show and edit the data.But on click of the button(custom button not the jquery model button) on the popup(that loads a partial view),the client side validation using dataAnnotation does not work. If I make a submit form like:-
$("#btnUpdate).submit(function (e) {
e.preventDefault();
var $form = $(this);
if ($form.valid()) {
//Add ajax call
}
});
Then after submit it redirects to:- { ../Employee/Edit/EmployeeId } where it shows a blank screen as I dont have any view for this.
I want that after the form post it should just refresh the jquery grid.
public PartialViewResult _CreateSupplier()
{
return PartialView(new Supplier());
}
[HttpPost]
public JsonResult _CreateSupplier(Supplier model)
{
//Validation
return Json(new
{
status = transactionStatus,
modelState = ModelState.GetModelErorrs()
}, JsonRequestBehavior.AllowGet);
}
Form post jquery method
$('#create-supplier').submit(function (e) {
e.preventDefault();
var $form = $(this);
if (!ModelIsValid($form))
return;
AjaxPost($form.serialize(), '#Url.Action("_CreateSupplier")', function (result) {
if (result.status == 0) {
$form[0].reset();
//Success
var grid = $("#gridSupplier").data("kendoGrid");
grid.dataSource.read();
} else if (result.status == 1)
AddFormErrors($form, result);
else if (result.status == 2)
//error;
});
});
Checking model method is valid and if invalid adding errors to form
function ModelIsValid(form) {
var validator = $(form).validate(); // obtain validator
var anyError = false;
form.find("input").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
if (anyError)
return false; // exit if any error found
return true;
}
function AddFormErrors(form, errors) {
for (var i = 0; i < errors.modelState.length; i++) {
for (var j = 0; j < errors.modelState[i].errors.length; j++) {
var val = $(form).find("[data-valmsg-for='" + errors.modelState[i].key + "']");
if (val.html().length > 0) {
$(form).find("[for='" + errors.modelState[i].key + "']").html(errors.modelState[i].errors[j]);
} else {
val.html('<span for="' + errors.modelState[i].key + '" generated="true" class="" style="">' + errors.modelState[i].errors[j] + '</span>');
}
}
}
}
Ajax post method:
function AjaxPost(postData, url, callback) {
$.ajax({
url: url,
type: 'POST',
data: postData,
dataType: 'json',
success: function (result) {
if (callback) callback(result);
}
});
}
And last c# generic method which checks returns model state errors
public static IEnumerable<object> GetModelErorrs(this ModelStateDictionary modelState)
{
return modelState.Keys.Where(x => modelState[x].Errors.Count > 0)
.Select(x => new {
key = x,
errors = modelState[x].Errors.Select(y => y.ErrorMessage).ToArray()
});
}
Hope answer is useful...

How to redirect an Ajax Method session on timeout

So I got a ajax method that returns a JSON result, but part of the method is to check if the session is valid.
So If a user refreshed a page, the ajax method is called, in which it throws an exception as the session has expired, now the method wants to return a JSON result, but instead I want to redirect them to the login page.
how do I do this?
public JsonResult GetClients()
{
var usertoken = new UserToken(this.User.Identity.Name);
if (usertoken.AccountId != null)
{
return new JsonResult() {Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
else
{
//Redirect Here
}
AFAIK you would only be able to do this via JavaScript since your call is using ajax, the solution to the other post would not work since the redirect header would not be honored for an ajax request.
You might want to add a status or hasExpire property to your return result:
[HttpPost]
public ActionResult GetClients()
{
var usertoken = new UserToken(this.User.Identity.Name);
if (usertoken.AccountId != null)
{
return Json(new { data = model, status = true });
}
else
{
return Json(new { data = null, status = false });
}
On your ajax call:
$.ajax('/controller/getclients', { }, function(data) {
if(data.status == true) {
// same as before you've got your model in data.data...
} else {
document.location.href = '/account/login';
}
});
Hope that help.
In Controller code, check for session validity. For example
if (Session["UserName"] == null)
{
return Json(new
{
redirectUrl = ConfigurationManager.AppSettings["logOffUrl"].ToString(),
isTimeout = true
});
}
In .js file check like the following
success: function (data) {
if (data != '' && typeof data != 'undefined') {
if (data.isTimeout) {
window.location.href = data.redirectUrl;
return;
}

How to add images in validation summary along with the error message?

I wanna display error message with success image(green tick mark) and failure image(Red warning) in validation summary. how to do this.
and i validation summary i will have to display some text in bold, italics etc. for that i tried to pass string like this.
inValid <b>username</b> or <b>password</b>
But in the page its rendering as it is. it is not showing username and password in bold. is there any way to do that. I am getting this validation error messages in controller and adding this to ModelState.add(error);
The ValidationSummary helper HTML encodes by default all messages. You could write a custom helper which doesn't HTML encode:
public static class HtmlExtensions
{
public static MvcHtmlString MyValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors, string message)
{
var formContext = htmlHelper.ViewContext.ClientValidationEnabled ? htmlHelper.ViewContext.FormContext : null;
if (formContext == null && htmlHelper.ViewData.ModelState.IsValid)
{
return null;
}
string messageSpan;
if (!string.IsNullOrEmpty(message))
{
TagBuilder spanTag = new TagBuilder("span");
spanTag.InnerHtml = message;
messageSpan = spanTag.ToString(TagRenderMode.Normal) + Environment.NewLine;
}
else
{
messageSpan = null;
}
var htmlSummary = new StringBuilder();
var unorderedList = new TagBuilder("ul");
IEnumerable<ModelState> modelStates = null;
if (excludePropertyErrors)
{
ModelState ms;
htmlHelper.ViewData.ModelState.TryGetValue(htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix, out ms);
if (ms != null)
{
modelStates = new ModelState[] { ms };
}
}
else
{
modelStates = htmlHelper.ViewData.ModelState.Values;
}
if (modelStates != null)
{
foreach (ModelState modelState in modelStates)
{
foreach (ModelError modelError in modelState.Errors)
{
var errorText = modelError.ErrorMessage;
if (!String.IsNullOrEmpty(errorText))
{
var listItem = new TagBuilder("li");
listItem.InnerHtml = errorText;
htmlSummary.AppendLine(listItem.ToString(TagRenderMode.Normal));
}
}
}
}
if (htmlSummary.Length == 0)
{
htmlSummary.AppendLine(#"<li style=""display:none""></li>");
}
unorderedList.InnerHtml = htmlSummary.ToString();
var divBuilder = new TagBuilder("div");
divBuilder.AddCssClass((htmlHelper.ViewData.ModelState.IsValid) ? HtmlHelper.ValidationSummaryValidCssClassName : HtmlHelper.ValidationSummaryCssClassName);
divBuilder.InnerHtml = messageSpan + unorderedList.ToString(TagRenderMode.Normal);
if (formContext != null)
{
// client val summaries need an ID
divBuilder.GenerateId("validationSummary");
formContext.ValidationSummaryId = divBuilder.Attributes["id"];
formContext.ReplaceValidationSummary = !excludePropertyErrors;
}
return MvcHtmlString.Create(divBuilder.ToString(TagRenderMode.Normal));
}
}
Now you have the possibility to use HTML tags in your validation messages:
ModelState.AddModelError("user", "invalid <b>username</b> or <b>password</b>");
and then:
<%= Html.MyValidationSummary(true, null) %>
Obviously by doing this you should ensure that your error messages contain valid HTML structure.
There is no doubt that #Darin Dimitrov answer is the best practice. but as a newbie i am gaining that functionaliy by using ViewBag
Inside Controller
if(true) //All is well and success msg is to be sent
{
ViewBag.Errors = null;
ViewBag.Success = "<b>Login</b> is Successful";
//Redirect
}
else
{
ViewBag.Errors = "<b>Some Error messages</b>";
ViewBag.Success = null;
}
Inside View()
#if(ViewBag.Errors != null)
{
<div class="error">#Html.Raw(#ViewBag.Errors)</div>
}
#if(ViewBag.Success != null)
{
<div class="success">#Html.Raw(#ViewBag.Success)</div>
}
Now the Css
.error { color: red; background-image:error_image.png; }
.success { color:green; background-image : success_image.png; }

Resources