mvc3 razor - url.action javascript error onClick event - javascript

I am having a problem with my url.action and my javascript onClick event call. What I am trying to do is pass my controller and actionresult method as a parameter for my javascript but I keep getting an error of:
Microsoft JScript runtime error: Syntax error, unrecognized expression: /UserManager/filterGrid
for this code:
<div class="webgrid-filter">
<input name="User logged in" type="checkbox" onclick="filterGrid('#Url.Action("filterGrid", "UserManager")')" id="chkboxGridFilter" />
</div>
view
#model IEnumerable<UserManager.Models.vw_UserManager_Model>
#*#model UserManager.Models.vw_UserManager_Model
*#
#{
ViewBag.Title = "User Manager Dashboard";
}
#Html.ActionLink("Create New User", "CreateUser")
<div class="webgrid-filter">
<input name="User logged in" type="checkbox" onclick="filterGrid('#Url.Action("filterGrid", "UserManager")')" id="chkboxGridFilter" />
</div>
<div class="webgrid-wrapper">
#{
ViewBag.Title = "Jobs";
WebGrid grid = new WebGrid(Model, canPage: true, canSort: true, rowsPerPage: 15, selectionFieldName: "selectedRow", fieldNamePrefix: "gridItem");
}
#grid.GetHtml(
fillEmptyRows: true,
tableStyle: "webgrid",
alternatingRowStyle: "webgrid-alternating-row",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
mode: WebGridPagerModes.All,
columns: new[] {
grid.Column("UserName"),
grid.Column("salutation"),
grid.Column("FirstName"),
grid.Column("LastName"),
grid.Column("Password"),
//grid.Column("isactive"),
//grid.Column(header: "Is logged in?", format: (model) => #Html.Raw("<input type='checkbox' checked='" + ((model.isactive) ? "checked" : "unchecked") + "' />")),
grid.Column(header: "User logged in", format: #<text><input name="User logged in"
type="checkbox" #(item.isactive == true ? "Checked" : null) onclick="logUserOff('#Url.Action("LogUserOff", "UserManager", new {userid = item.userid} )')" id="chkboxIsActive" /></text>),
grid.Column("isApproved"),
grid.Column("MaxConcurrentUsers"),
grid.Column("email"),
grid.Column("group_name"),
grid.Column("module_name"),
grid.Column(header:"Edit", format:#<text><div id="btnEditSelectedRow">
"#Html.ActionLink("Edit record", "EditUser", "UserManager", new {
userid = item.userid,
salutation = item.salutation,
firstname = item.FirstName,
lastname = item.LastName,
password = item.Password,
isactive = item.isactive,
isapproved = item.IsApproved,
maxconcurrentusers = item.MaxConcurrentUsers,
email = item.email,
module = item.module_name,
group = item.group_name }, null)</div></text>),
grid.Column(header:"Delete", format:#<text><div id="btnDelSelectedRow">
"#Html.ActionLink("Delete record", "DeleteUser", "UserManager", new {
userid = item.userid,
username = item.UserName,
salutation = item.salutation,
firstname = item.FirstName,
lastname = item.LastName,
password = item.Password,
isactive = item.isactive,
email = item.email,
module = item.module_name,
group = item.group_name }, null)</div></text>)
})
</div><br />
<script type="text/javascript">
$(document).ready(function () {
// Disable checkboxs where a user is not active.
$(".webgrid-wrapper input:not(:checked)").attr("disabled", "disabled");
// Style tables.
function jQueryUIStyling() {
$('input:button, input:submit').button();
$('.webgrid-wrapper').addClass('ui-grid ui-widget ui-widget-content ui-corner-all');
$('.webgrid-title').addClass('ui-grid-header ui-widget-header ui-corner-top');
jQueryTableStyling();
} // end of jQueryUIStyling
function jQueryTableStyling() {
$('.webgrid').addClass('ui-grid-content ui-widget-content');
$('.webgrid-header').addClass('ui-state-default');
$('.webgrid-footer').addClass('ui-grid-footer ui-widget-header ui-corner-bottom ui-helper-clearfix');
} // end of jQueryTableStyling
});
</script>
<script type="text/javascript">
function logUserOff(url) {
var answer = confirm('Are you sure you want to save this data?')
if (answer) {
// alert(url + ": " + value);
$.ajax({
url: url,
type: "POST"
// data: value
}).done(function () {
$(this).addClass("done");
});
return true;
}
else {
return false;
}
};
</script>
<script type="text/javascript">
function filterGrid(url) {
alert($(url).val());
}
</script>
This is the javascript:
<script type="text/javascript">
function filterGrid(url) {
alert($(url).val());
}
</script>
Error originates from jquery-1.5.1:
throw"Syntax error, unrecognized expression: "+a
Anyone know what I am doing wrong? Thanks!

this error id caused the way you are showing the value of your URL in the alert.
You should write it like this
function filterGrid(url) {
alert(url);
}

Related

How to send params form web page to parse cloud function?

I make a web form to add some string to database and now my add function is running perfectly but my web does not send params to function when i click submit and console log send undefined to me i dont know what to do please help and thank you
Here my function code and run perfectly
Parse.Cloud.define('addSynonym', function (request, response) {
var SYN = Parse.Object.extend("Synonym");
var CommonwordFromUser = request.params.common_word;
var SynonymwordFromUser = request.params.synonym_word;
console.log(CommonwordFromUser);
console.log(SynonymwordFromUser);
if (CommonwordFromUser == null || SynonymwordFromUser == null) {
response.error("request null values");
} else {
var query = new Parse.Query(SYN)
query.find({
success: function (synResponse) {
var synOBJ = new SYN();
synOBJ.set("common_word", CommonwordFromUser);
synOBJ.set("synonym_word", SynonymwordFromUser);
synOBJ.save(null, {
success: function (success) {
response.success({
"common_word": CommonwordFromUser,
"synonym_word": SynonymwordFromUser
});
},
error: function (error) {
response.error("save failed : " + error.code);
}
});
}
})
}
});
Here my web form my problem
<form id="contact" class="registerForm">
<div class="alert alert-success" id="alertbox">
<strong>Success!</strong> Your Synonym has uploaded.
</div>
<div class="text-center">
<img src="img/icon.png" class="text-center" alt="Responsive image" width="90" height="90">
</div>
<h3 class="text-center font-weight-normal">Welcome to synonym Menu</h3>
<label id="label-tags" for="ask-tags">Common Word :</label>
<fieldset class="form-group">
<input id="common_word" name="common_word" placeholder="Please type some word" type="text" tabindex="1" required>
</fieldset>
<label id="label-tags" for="ask-tags">Synonym Word :</label>
<fieldset class="form-group">
<input id="synonym_word" name="synonym_word" placeholder="Please type some word" type="text" tabindex="2"
required>
</fieldset>
<fieldset class="form-group">
<button name="submit" type="submit" onclick="submitfrom()" id="contact-submit">Submit</button>
</fieldset>
</form>
</div>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<script src="js/standalone/selectize.min.js"></script>
<script src="js/bootstrapValidator.min.js"></script>
<script>
$('.registerForm').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
common_word: {
validators: {
notEmpty: {
message: 'Require !!'
}
}
},
synonym_word: {
validators: {
notEmpty: {
message: 'Require !!'
}
}
},
}
}).on('success.form.bv', function (e) {
submitfrom();
});
$('#alertbox').hide();
function submitfrom() {
var common_word = $('#common_word').val();
var synonym_word = $('#synonym_word').val();
var obj = [{
"common_word": common_word,
"synonym_word": synonym_word,
}];
var data = '{"objects":' + JSON.stringify(obj) + '}';
callParseServerCloudCode("addSynonym", data, function (response) {
if (response) {
console.log(response);
alert("🤖:Ok !");
location.reload();
}
});
$(this).scrollTop(0);
$('.registerForm').data('bootstrapValidator').resetForm();
$('#alertbox').show();
$('#alertbox').fadeTo(2000, 500).slideUp(500, function () {
$('#alertbox').hide();
});
}
function callParseServerCloudCode(methodName, requestMsg, responseMsg) {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://xxxxxxxxxxxx.herokuapp.com/parse/functions/' + methodName, true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.setRequestHeader('X-Parse-Application-Id', 'myAppId');
xhr.setRequestHeader('X-Parse-Master-Key', 'myMasterKey');
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
responseMsg(myArr.result);
}
};
xhr.send(requestMsg);
}
</script>
</body>
</html>
Option 1:
Just change the lines below and it should work
var obj = {
"common_word": common_word,
"synonym_word": synonym_word,
};
var data = JSON.stringify(obj);
Option 2 (recommended):
Install Parse JS SDK: https://docs.parseplatform.org/js/guide/#getting-started
Call cloud code like this:
Parse.Cloud.run(
"addSynonym",
{
"common_word": common_word,
"synonym_word": synonym_word
}
).then(
function() {
console.log('success');
},
function (error) {
console.error(error);
}
);

how to remove specific character and text

I have finish autocomplete with a jquery library which is
using jquery-ui-1.12.1.min.js
. I have modified it to make to get the search with username and full name. it will show as below image
when I select the value it will paste the whole text into an input box.
here is my question how do it modify it to show as the image but when I select the value it will only paste the username into input box?
how i only want nonstop00000 paste it into input box when i select the 1st value
here is my javascript
$(document).ready(function () {
$("#id").autocomplete({
source: function(request,response) {
$.ajax({
url: '#Url.Content("~/UserManagement/AutoCompleteUser")/',
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return [{ label: item.Username + " | " + item.FullName, value: item.id }];
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
here is my search controller
if (!String.IsNullOrEmpty(searchString))
{
user = user.Where(s => s.Username.Trim().Contains(searchString.Trim())
|| s.FullName.Trim().Contains(searchString.Trim()));
}
here is my autocomplete controller
public JsonResult AutoCompleteUser(string term)
{
var result = (from r in db.UserTables
where ((r.Status == "Active") && (r.Username.ToLower().Contains(term.ToLower()) || (r.FullName.ToLower().Contains(term.ToLower()))))
select new { Username = r.Username, FullName = r.FullName }).Distinct();
return Json(result);
}
here is my view
<div class="col-lg-9 col-md-9 col-sm-9 col-xs-12 search-panel">
#using (Html.BeginForm("Index", "UserManagement", FormMethod.Get))
{
<div class="input-group form-group ui-widget">
#Html.TextBox("id", ViewBag.CurrentFilter as string, new { #class = "form-control autocomplete", #placeholder = "Search for..." })
<span class="input-group-btn">
<input type="submit" value="Search" class="form-control autocomplete " />
</span>
</div>
}
</div>
To achieve this you can use the select event to amend the value to be placed in to the input. Try this:
$("#id").autocomplete({
// your settings...
select: function(e, ui) {
e.preventDefault();
$('#id').val(ui.item.label.split('|')[0].trim());
}
});

implementing delete operation in web grid

I am implementing deletion functionality on web grid.
I have a column which has a link delete when it is clicked a JavaScript function is called which sends the id of that record to controller who calls a remove method to delete that record but when i debug the code list of vehicles are returned but when delete link is clicked
it gives a error A data source must be bound before this operation can be performed.
view:
#model IEnumerable<ParkOnMyDrive.Models.Vehicle>
#{
ViewBag.Title = "ViewVehicle"
}
<h2>ViewVehicle</h2>
#{
var grid = new WebGrid(source: Model,
defaultSort: "make",
rowsPerPage: 3);
}
<h2>Vehicle List</h2>
<div id="grid">
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("vehicleType","Type"),
grid.Column("make", " Make"),
grid.Column("modelType", "Model"),
grid.Column("color", "Color"),
grid.Column("registartion", "Registartion"),
grid.Column(
header: "Action",
format: #<text>
<a href="#" id="Delete_#item.vehicleId" >Delete</a></text>)
)
)
Controller:
[HttpPost]
public ActionResult DeleteVehicle(string vehcKey)
{
//string key = "eb306a32-1be0-47ad-a0e8-756af97643b8";
Vehicle vehicleModel = new Vehicle();
string userName = "wasfa_anjum#yahoo.com";
if (ModelState.IsValid)
{
bool success = vehicleModel.RemoveVehicle(vehcKey,userName);
if (success)
{
ModelState.AddModelError("", "Vehicle deleted successfully");
}
else
{
ModelState.AddModelError("", "Vehicle not deleted");
}
}
else
{
}
return View();
}
Model
public bool RemoveVehicle(string vehicleKey,string userName)
{
bool success = false;
using (var session = MvcApplication.Store.OpenSession())
{
var removeVehicle = from vehc in session.Query<Vehicle>()
where vehc.vehicleId == vehicleId
where vehc.userId == userName
select vehc;
if (removeVehicle.Count() > 0)
{
var myVehicle = removeVehicle.FirstOrDefault();
Session.Delete(myVehicle);
Session.SaveChanges();
success = true;
}
}

how to get id from webgrid with javascript

i try to make webgrid and when i click edit button, the button will pass value from first td in webgrid to my controller, but i cant pass the value.. can some one tell me, what line is error?
this my view
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
mode: WebGridPagerModes.All,
columns: grid.Columns(
grid.Column(header: "Content ID", format: (item) => item.ContentID),
grid.Column(header: "Active", format: (item) => Html.Raw("<input type=\"checkbox\" " + ((item.Active == true) ? "checked='cheked'" : "") + "disabled = 'disabled'/>")),
grid.Column(header: "Image", format: #<img src="#Href("~/images/MobileContent/" + #item.ImageURL)" width="120px" height="50px;" />),
grid.Column("Description"),
grid.Column("Action", format: #<text>
<button class="edit-content">Edit</button>
<button class="remove-content">Remove</button>
</text>)
)
)
}
</div>
</div>
</div>
</div>
</div>
</div>
#section scripts{
<script>
$(".edit-content").click(function () {
var id = $(this).find('td:first').text();
location.href = '/MobileContent/Edit/' + id;
});
$('thead tr th:nth-child(1), tbody tr td:nth-child(1)').hide();
</script>
}
this my controller
public ActionResult Edit(int id)
{
ViewModel.MobileContent.MobileContentViewModel vm = new ViewModel.MobileContent.MobileContentViewModel();
vm.EditContent = EditContent(id);
return View(vm);
}
Have a try
var id = $(this).parent('tr').find('td:first').text();
Try this,
<input type="button" value="Assign" onclick="myfunction(#item.ID);" />
OR
#Html.ActionLink("EditUser", "DYmanicControllerPage", "Test", new { Id = item.ID }, new { #class = "hide" })
function myfunction(obj) {
var id = obj;
location.href = '#Url.Action("DYmanicControllerPage", "Test")?Id=' + id;
}
Controller
public ActionResult DYmanicControllerPage(string Id)
{
var model = new RegisterModel();
int _ID = 0;
int.TryParse(Id, out _ID);
if (_ID > 0)
{
RegisterModel register = GetRegisterUserById(_ID);
model.ID = _ID;
model.Name = register.Name;
model.Address = register.Address;
model.PhoneNo = register.PhoneNo;
}
return View(model);
}

Partial View not working propely in index view.

I am developing MVC application and using razor syntax.
In this application I am giving comment facility.
I have added a partial view, which loads the comment/Records from DB.
In below image, we can see the comment box which is called run-time for employee index view.
Now as we can see comment box, I called at run-time, which is partial view, but problem is I can add comment for only on first record...after first record that button wont work at all...
anything is missing ?
Is there separate process when we call any partial view run-time and make in action on it ?
See the pic...
Here is the code....
#model PagedList.IPagedList<CRMEntities.Customer>
<link href="../../Content/Paging.css" rel="stylesheet" type="text/css" />
<link href="../../Content/EventEntity.css" rel="stylesheet" type="text/css" />
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")%>" type="text/javascript"></script>
<div id="ListBox">
<div id="ListHeader">
All customers(#Model.TotalItemCount)
</div>
#foreach (var item in Model)
{
<div id="ListContent">
<span class="ContentTitleField">#Html.ActionLink(item.Name, "Details", new { id = item.Id }, new { #style="color:#1A6690;" })</span>
#if (item.Owner != null)
{
<span class="ContentSecondaryField">#Html.ActionLink(item.Owner.FullName, "Details", "Employee", new { id = item.OwnerId }, new { #style = "color:#1A6690;" })</span>
}
<span class="ContentSecondaryField">#Html.DisplayFor(modelItem => item.Address)</span>
<span id="flagMenus">
#Html.Action("ShowFlag", "Flagging", new { entityId=item.Id, entityType="Customer"})
</span>
#if (item.Opportunities.Count > 0)
{
<span class="FlagOpportunity">#Html.ActionLink("opportunities(" + item.Opportunities.Count + ")", "Index", "Opportunity", new { custid = item.Id }, new { #style = "color:#fff;" })</span>
}
<div style="float:right;">
#Html.Action("SetRate", "Rating", new { entityId = item.Id, rating = item.Rating, entityname = "Customer" })
</div>
<div id="subscribeStatus" style="float:right;">
#Html.Action("ShowSubscribedStatus", "Subscribing", new { entityId = item.Id, entityType = "Customer" })
</div>
<div class="ListLinks">
<span class="ListEditLinks">
<span style="float:left;">#Html.ActionLink("edit", "Edit", new { id = item.Id })</span>
<span class="LinkSeparator"></span>
</span>
<span class="ListAddLinks">
<span style="float:left;">#Html.ActionLink("+opportunity", "Create", "Opportunity", new { custid = item.Id }, null)</span>
<span class="LinkSeparator"></span>
<span>#Ajax.ActionLink("+Comment", null, null, null, new { id = item.Id, #class = "addremark" })</span>
</span>
<div class="RemarkBox"></div>
</div>
<span class="CommentAdd">
</span>
<div class="CommentBlock">
</div>
<span>#Ajax.ActionLink("Add Comment", null, null, null, new { id = item.Id, #class = "addremark" })</span>
</div>
}
<div class="PagingBox">
#Html.Action("CreateLinks", "Pager", new { hasPreviousPage = Model.HasPreviousPage, hasNextPage = Model.HasNextPage, pageNumber = Model.PageNumber, pageCount = Model.PageCount })
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.RemarkBox').hide();
$('a.addremark').click(function () {
var url="#Html.Raw(Url.Action("ShowCommentBox", "Comment", new { Id = "idValue", EntityType = "Customer" }))";
url=url.replace("idValue",event.target.id);
$('.RemarkBox').load(url);
$(this).closest('div').find('div.RemarkBox').slideToggle(300);
return false;
});
$("a.pagenumber").click(function () {
var page = 0;
page = parseInt($(this).attr("id"));
$.ajax({
url: '#Url.Action("GetPagedCustomers")',
data: { "page": page },
success: function (data) { $("#customerlist").html(data); }
});
return false;
});
});
</script>
To expand on what Alberto León is saying, the partial page load will not cause the document ready event to fire, so the re-rendered elements will not have the javascript event handlers registered after the first comment is added.
To resolve this, you could put the event registration code into a function, and call this both from the document ready event and the success handler of the AJAX call. Something like this:
function AssignEventHandlers() {
$('a.addremark').click(function () {
....
});
$("a.pagenumber").click(function () {
var page = 0;
page = parseInt($(this).attr("id"));
$.ajax({
url: '#Url.Action("GetPagedCustomers")',
data: { "page": page },
success: function (data) {
$("#customerlist").html(data);
AssignEventHandlers();
}
});
return false;
});
}
$(document).ready(function () {
$('.RemarkBox').hide();
AssignEventHandlers();
}
In success function you need to recall the javascript, or the jquery code that makes the button work. Is an error that taked me a lot of time. Anything uploaded by ajax or any renderpartiAl needs to recall javascript.
$('.RemarkBox').load(url, function() {
//RECALL JAVASCRIPT
});

Categories