Hide/Show Editable links in webGrid CSHTML code - asp.net-mvc

I am trying to Hide/Show the 'Edit' link in each row of a given Grid. Basically only few user roles have the access to Modify the information. I wrote a method ActionResult in controller class to check the user access and returning Boolean value. Based on True/False I need to Hide/Show the 'Edit' Links in a grid. The design code is written in MVC CSHTML. Please suggest how it can be achieved. I tried using JQuery but I can hide the Edit column only for the first row of the grid. Below is the code in CSHTML and Jquery.
CSHTML Code
<table border="1" cellpadding="0" cellspacing="1" style="width: 90%;"><tr>
<td>
#grid.GetHtml(tableStyle: "webGridMedium",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
columns: grid.Columns(
grid.Column("BeginDate", "Begin Date", style: "description"),
grid.Column("Status", "Status", style: "description"),
grid.Column("", style: "description10", format: #<a class="edit-status" id="btnEditStatus" href="">Edit</a>)
))
</td>
</tr>
</table>
JQuery Code: The parameter data is boolean value I get it from Controller class.
<script>
$(document).ready(function () {
checkAccess();
}
function checkAccess() {
// debugger;
$.ajax({
url: '/Employee/CheckAccess',
type: 'POST',
data: {},
success: function (data) {
if (data == false) {
document.getElementById("btnEditStatus").style.visibility = "hidden";
}
else if (data = true) {
document.getElementById("btnEditStatus").style.visibility = "";
}
},
error: (function (result) {
alert("Failed access! Please contact administrator.");
})
})
}
</script>

<script>
function checkAccess() {
// debugger;
$.ajax({
url: '/Application/CheckAccess',
type: 'POST',
data: {},
success: function (data) {
if (data == false) {
$('.modaltable tr').each(function (i, row) {
$(this).find('.edit-status').hide();
});
}
else if (data = true) {
// your code
}
},
error: (function (result) {
alert("Please contact IT administrator for access.");
})
})
}
</script>

Related

How Bind Model data to Telerik Controls?

I am using bellow code to insert the data to db. While Clicking the save button the data should be bind to the model and needs to be posted to controller action . But the data is not bind to the model. What is the issue in the bellow code . Any please help me to solve the below issue.
#(Html.Kendo().TextBoxFor(model => model.Code)
.HtmlAttributes(new { placeholder = "Enter Code", required = "required",
validationmessage="Code is Required" })
)
<input type="button" title="Save" id="btnsave" value="Save" onclick="submit()"/>
<script>
function submit(data) {
debugger;
console.log("Cosoledata "+JSON.stringify(data))
$.ajax({
type: "POST",
url: '#Url.Action("action", "controller")',
data: { data: #Model },
dataType: "json",
success: function (response) {
}
});
}
</script>
data: { data: #Model },
In the JavaScript script, you can directly get the Model data via the #Model.
To send the model data to the controller method, you could create a JavaScript object, then use JQuery to get the related property value (such as Code), then send the object to the controller method.
Please refer the following sample:
View page:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$("#btnCreate").click(function () {
var review = {}; //create a JavaScript Object.
//user JQuery to get the entered value, and set the property value.
review.ReviewID = $("#ReviewID").val();
review.MovieID = $("#MovieID").val();
review.goreRating = $("#goreRating").val();
review.shockRating = $("#shockRating").val();
review.jumpRating = $("#jumpRating").val();
review.plotRating = $("#plotRating").val();
review.supernaturalRating = $("#supernaturalRating").val();
review.starRating = $("#starRating").val();
//if you want to send multiple objects, you could create an array.
//var reviewlist = [];
//reviewlist.push(review);
$.ajax({
url: "/Home/AddReview",
method: "Post",
data: { "reviewViewModel": review } , // { "reviewViewModel": reviewlist },
success: function (response) {
alert(response);
},
error: function (response) {
console.log("error");
}
})
});
})
</script>
}
Controller method:
[HttpPost]
public IActionResult AddReview(ReviewViewModel reviewViewModel)
{
if (ModelState.IsValid)
{
//do something
}
return View();
}
The result as below:

C# razor select2 disable

Is there a way I can set this select2 to be disable read-only if there is a value in option.AgentName? I have add the selectElement.select2 method is there anything I can add to the callback?
Is this the correct way to do this? using self.entry.Agent.AgentName != ""?
View
<div class="form-group sentence-part-container sentence-part ng-scope ui-draggable sentence-part-entry-agent sentence-part-with-select2-single" [class.has-errors]="entry.IsInvalid && entry.IsTouched">
<div class="sentence-part-values">
<div class="sentence-part-values-select2-single">
<select class="form-control" style="width: 300px" [(ngModel)]="entry.Agent.VersionKey">
<option *ngFor="let option of agents" [value]="option.VersionKey">{{option.AgentName}}</option>
</select>
</div>
</div>
</div>
ts file
$selectElement.select2({
initSelection: function(element, callback) {
console.log(self.entry.Agent.AgentName);
if (self.entry.Agent.AgentName != "")
{
console.log('disabled');
$selectElement.prop('disabled', true);
}
callback({ id: self.entry.Agent.VersionKey, text: self.entry.Agent.AgentName });
},
placeholder: "Select an agent"
})
.on("change", (e) => {
self.ngZone.run(() => {
self.entry.Agent.VersionKey = $selectElement.val();
self.entry.AgentVersionKey = self.entry.Agent.VersionKey;
let regimenEntryAgent = this.getRegimenEntryAgentByVersionKey(self.entry.Agent.VersionKey);
if (regimenEntryAgent) {
self.entry.Agent.AgentId = regimenEntryAgent.AgentId;
}
self.onSentenceChange(null);
});
})
.on("select2:close", () => {
self.entry.IsTouched = true;
this.validate();
});
You might try to apply some logic in newData.push() method of Select2.
ajax: {
url: '/DemoController/DemoAction',
dataType: 'json',
delay: 250,
data: function (params) {
return {
query: params.term, //search term
page: params.page
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
// apply some logic to the corresponding item here
if(item.AgentName == "x"){
}
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.AgentName
});
});
return { results: newData };
},
cache: true
},
Update:
It is recommended that you declare your configuration options by passing in an object when initializing Select2. However, you may also define your configuration options by using the HTML5 data-* attributes.
For the other Select2 options look Options.

Render a partial view inside a Jquery modal popup on top of a parent view

I am rendering a partial view on top of the parent view as follows on a button click:
$('.AddUser').on('click', function () {
$("#AddUserForm").dialog({
autoOpen: true,
position: { my: "center", at: "top+350", of: window },
width: 1000,
resizable: false,
title: 'Add User Form',
modal: true,
open: function () {
$(this).load('#Url.Action("AddUserAction", "UserController")');
}
});
});
When user click AddUser button i am giving a jquery modal pop up with partial view rendered in it. But when user click save on partial view I am saving the entered information into database. But i have to show the pop up again on the parent view to add another user, until they click on cancel. Please help me how to load the partial view on top of the parent view.
Thanks
I suggest you create a jquery ajax function to post form data, then use the call back function to clear the form data. This way unless the user clicks the cancel button, the dialog is always showing.
See below example:
Main View
<button class="AddUser">Add User</button>
<div id="AddUserForm"></div>
Partial View (AddUserPartialView)
#model Demo.Models.AddUserViewModel
<form id="myForm">
<div id="AddUserForm">
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name)
</div>
</form>
Js file
$('.AddUser').on('click', function () {
$("#AddUserForm").dialog({
autoOpen: true,
position: { my: "center", at: "top+350", of: window },
width: 1000,
resizable: false,
title: 'Add User Form',
modal: true,
open: function () {
$(this).load('#Url.Action("AddUserPartialView", "Home")');
},
buttons: {
"Add User": function () {
addUserInfo();
},
Cancel: function () {
$(this).dialog("close");
}
}
});
return false;
});
function addUserInfo() {
$.ajax({
url: '#Url.Action("AddUserInfo", "Home")',
type: 'POST',
data: $("#myForm").serialize(),
success: function(data) {
if (data) {
$(':input', '#myForm')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
}
}
});
}
Action
public PartialViewResult AddUserPartialView()
{
return PartialView("AddUserPartialView", new AddUserViewModel());
}
[HttpPost]
public JsonResult AddUserInfo(AddUserViewModel model)
{
bool isSuccess = true;
if (ModelState.IsValid)
{
//isSuccess = Save data here return boolean
}
return Json(isSuccess);
}
Update
If you want to show the error message when errors occurred while saving the data, you could change the Json result in AddUserInfo action like below:
[HttpPost]
public JsonResult AddUserInfo(AddUserViewModel model)
{
bool isSuccess = false;
if (ModelState.IsValid)
{
//isSuccess = Save data here return boolean
}
return Json(new { result = isSuccess, responseText = "Something wrong!" });
}
then add a div element in your partial view:
#model MyParatialView.Controllers.HomeController.AddUserViewModel
<div id="showErrorMessage"></div>
<form id="myForm">
<div id="AddUserForm">
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name)
</div>
</form>
finally, the addUserInfo JS function should be like :
function addUserInfo() {
$.ajax({
url: '#Url.Action("AddUserInfo", "Home")',
type: 'POST',
data: $("#myForm").serialize(),
success: function (data) {
if (data.result) {
$(':input', '#myForm')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
} else {
$("#showErrorMessage").append(data.responseText);
}
}
});
}

How do I get all values of checkbox those are checked using ajax/jQuery in asp.net mvc

Ajax post:
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
// var vals = [];
// $('input:checkbox[name=Blanks]:checked').each(function () {
// vals.push($(this).val());
// });
// alert(vals);
//
var checkboxData = $(':checked').val();
$.ajax({
// Check the value.
type: 'POST',
url: '/Home/Extract',
data: { 'name': checkboxData },
// contentType: 'application/json; charset=utf-8', // No need to define contentType
success: function (result) {
},
error: function (err, result) {
alert("Error in delete" + err.responseText);
}
});
});
Controller method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Extract(string[] name)
{
}
My problem is that I am getting null values in my string[] name when I use array and single checkBox values when I use other case. Any suggestions or ideas as to why the post looks good?
View:
<input type="button" id="btn" value="Extract" style="float:right "/>
#foreach (var m in (List<string>)ViewData["list"])
{
<ul>
<li>
<input type="checkbox" class="myCheckbox" name="Blanks" id="chk" value="#m"/>
<img src="#m" alt=""/>
First start by fixing your markup and remove the id="chk" from your checkboxes because you cannot have 2 elements with the same id.
Alright, and then simply generate a javascript array containing the values of the selected checkboxes and POST this array to the server:
$('#btn').click(function () {
var values = $('input[type="checkbox"].myCheckbox:checked').map(function() {
return $(this).val();
}).toArray();
$.ajax({
type: 'POST',
url: '/Home/Extract',
data: JSON.stringify({ name: values }),
contentType: 'application/json',
success: function (result) {
},
error: function (err, result) {
alert("Error in delete" + err.responseText);
}
});
return false;
});
And your controller action signature might look like this:
[HttpPost]
public ActionResult Extract(string[] name)
{
...
}
But all this would have been completely unnecessary if you had used a view model and the strongly typed Html.CheckBoxFor helper.

Ajax displays div dialog in mvc view

Pretty new to ajax.
So I have this div:
<div id="authentication" title="Authentication" >
<b>Please Generate a new token to continue!</b>
<br /><br />
<table>
<tr>
<td>Token:</td>
<td><input type="text" id="txtToken"/></td>
</tr>
<tr>
<td></td>
<td><label id="lblError"></label></td>
</tr>
</table>
</div>
which is not being displayed on my mvc view because it is a being used as a dialogue box by Ajax code below:
$('#authentication').dialog({
autoOpen: true,
width:500,
resizable: false,
beforeclose : function() { return false; },
title: 'Authentication',
modal: true,
buttons: {
"Cancel": function () {
window.location.replace("#Url.Action("Index", "Home")");
},
"Submit": function () {
var token=$('#txtToken').val();
var dlg = $(this);
$.ajax({
type: 'POST',
data: { 'token': token},
dataType: 'json',
url: '#Url.Action("CheckNewToken", "Account")',
success: function (result) {
if(result==true)
{
window.parent.jQuery('#authentication').dialog('destroy');
}
else{
$('#lblError').html("Incorrect credentials. Please try again");
}
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
}
});
However when the codes goes to success and result == result, the dialog box is destroyed but the div (dialog box) is then being displayed on my view which I don't want. What am I doing wrong?
Close the dialog and then destroy. This will hide the dialog completely and then destroy its dialog features. if you just do .dialog('destroy') it will just remove the dialog functionality completely and display the element as is on the page but it wont hide.
success: function (result) {
if(result==true)
{
$('#authentication').dialog('close').dialog('destroy');
}
else{
$('#lblError').html("Incorrect credentials. Please try again");
}
},
Another thing is beforeclose : function() { return false; }, you are returning false which will prevent the close event from happening. it should be beforeClose though you can remove it safely.
if the above doesnt work another option to remove the div is by subscribing to close event:-
$('#authentication').dialog({
autoOpen: true,
width:500,
resizable: false,
title: 'Authentication',
modal: true,
close:function(){
$(this).dialog('destroy').hide();
},
buttons: {
"Cancel": function () {
},
"Submit": function () {
var token=$('#txtToken').val();
var dlg = $(this);
$('#authentication').dialog('close');
}
}
});

Resources