How to set Html class with a javascript function? - c#

i display 4 buttons for each elements in a list.
i want to know which button has data inside so i create an ActionResult and this returns true if contains data.
[HttpPost]
public ActionResult TieneNotificacion(string Pnombre, string Pcorreo1, string Pprefijo)
{
var lista = agp.CC15_EscalaMandoPorUsuario(Pnombre,Pcorreo1,Pprefijo);
if(lista != null){
return Json(true);
}
else{
return Json(false);
}
}
in the view i want to set the button class "btn btn-xs" if the method return false and "btn btn-xs btn-info" if return true.
$(document).ready(function () {
function tieneNotificacion(Nombre,Correo1,Prefijo){
$.ajax({
type: "POST",
url: "/CentralSoluciones/TieneNotificacion",
data: { Pnombre: Nombre,
Pcorreo1: Correo1,
Pprefijo: Prefijo },
success: function (data) {
if (data) {
return "btn btn-xs btn-info"
}
else {
return "btn btn-xs"
}
}
});
}
});
and the html tag is like that:
<a href="#Url.Action("Detalles", new { Pnombre= item.Nombre, Pcorreo1=item.Correo1, Pprefijo=list.Prefijo })"
class=tieneNotificacion(#item.Nombre,#item.Correo1,#list.Prefijo)>
<span>#list.Prefijo</span>
</a>

You can set the class for your button within the AJAX call.
Suppose you have these buttons
<input type="button" />
<input type="button" />
<input type="button" />
Update your javascript to
$(document).ready(function () {
function tieneNotificacion(Nombre,Correo1,Prefijo){
$.ajax({
type: "POST",
url: "/CentralSoluciones/TieneNotificacion",
data: { Pnombre: Nombre,
Pcorreo1: Correo1,
Pprefijo: Prefijo },
success: function (data) {
if (data) {
$( ":button" ).addClass("btn btn-xs btn-info");
//To set a class completely, instead of adding one or removing one.
// use this $( ":button" ).attr('class','btn btn-xs btn-info');
}
else {
$( ":button" ).addClass("btn btn-xs");
//To set a class completely, instead of adding one or removing one.
// use this $( ":button" ).attr('class','btn btn-xs');
}
}
});
}
});
JSFiddle

Related

PartialView is not showing in Asp.net MVC?

I have an array which as the number(Id's of some tags) and I am passing this array to the action method using ajax call when this array passed to the controller action method(RawTagCreation) and then the numbers in this arrays are used to get data from database and then pass to another ViewModel object (rawTagVMs) and then I am returning the partial view with this ViewModel object. The problem is that the partial view is not showing?
Basically success event of ajax call is also not fired.
function selectedValues() {
var datas = [];
$('#search_to option').each(function () {
datas.push($(this).attr('value'));
});
console.log(datas);
if (datas.length > 0) {
$.ajax({
url: "#Url.Action("RawTagCreation", "SourceTagMapping")",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({ 'selectedTags': datas }),
success: function (data) {
debugger;
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});
}
else {
alert('Please Select One or More Raw Tags')
}
}
The action method is given here
public ActionResult RawTagCreation(int[] selectedTags)
{
List<RawTagVM> rawTagVMs = new List<RawTagVM>();
if (ModelState.IsValid)
{
foreach (var item in selectedTags)
{
var OldSourecTag = db.Real_Raw_Points.Where(x => x.Source_Tag_Id_Fk == item).FirstOrDefault();
var OPCTag = db.OPC_SourceTags.Where(x => x.Source_Tag_Id == item).FirstOrDefault();
if (OldSourecTag == null)
{
RawTagVM objToInsertRawTags = new RawTagVM();
objToInsertRawTags.Source_Tag_Id_Fk = item;
objToInsertRawTags.R_Tag_Name = "Provide Tag Name";
rawTagVMs.Add(objToInsertRawTags);
}
}
return PartialView("_Update_TagNames", rawTagVMs);
}
return View();
}
PartialView is here
#model List<OmniConnect.ViewModel.RawTagViews.RawTagVM>
<div class="modal-header">
<h3 class="modal-title" id="exampleModalLabel">Update The Raw Tag Names</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="Confirm()">Confirm Update</button>
</div>
when you try ajax call
you can't return partial view
if you want return a view you must use form like Html.Beginform
and submit
if you want return success method you must return a value may be string
and append it to a tag
public ActionResult RawTagCreation(int[] selectedTags)
{
List<RawTagVM> rawTagVMs = new List<RawTagVM>();
if (ModelState.IsValid)
{
return Json("<div>any view</div");
}
return json("");
}
and then you can use like this:
$.ajax({
url: "#Url.Action("RawTagCreation", "SourceTagMapping")",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({ 'selectedTags': datas }),
success: function (data) {
debugger;
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});

Send data to ajax controller

The program does the following steps:
The user clicks on Change Address
The button disappears, another button appears - Save.
Next, the program should read the data from the input and send it via ajax to the controller method.
But nothing works. When I put everything in one <script> tag, the first button also stops working. Help
The problem is that even the buttonSetAddress button does not perform the function. It starts working only after I remove everything else from <script>
<div class="form-group">
<label>Адресс</label>
<input class="form-control" id="AddressInput" type="text" placeholder="#ViewBag.User.Address" readonly /><br />
<button type="button" class="btn btn-primary" id="buttonSetAddress">Изменить</button>
<button type="button" class="btn btn-success" id="buttonSaveAddress" onclick="SaveAddress()" hidden>Сохранить</button>
</div>
js and ajax
<script type="text/javascript">
document.getElementById('buttonSetAddress').onclick = function AddressInputSet() {
document.getElementById('AddressInput').removeAttribute('readonly');
document.getElementById('buttonSetAddress').hidden = 'true';
document.getElementById('buttonSaveAddress').removeAttribute('hidden');
alert('sdfgdfg');
};
document.getElementById('buttonSaveAddress').onclick = function SaveAddress() {
var data = JSON.stringify( {
userId: #ViewBag.User.Id,
address: document.getElementById('AddressInput').value
});
$.ajax({
type: 'POST',
url: '/Account/ResetAddress',
data: data,
dataType: JSON,
success: function () {
document.getElementById('buttonSaveAddress').hidden = 'true';
},
error: function () {
alert('Error');
}
});
};
</script>
Controller
[HttpPost]
public async void ResetAddress(string userId, string address)
{
var user = await _userManager.FindByIdAsync(userId);
user.Address = address;
await _userManager.UpdateAsync(user);
}
contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.
dataType is what you're expecting back from the server: json, html, text, etc. jQuery will use this to figure out how to populate the success function's parameter.
Since your action return void, you could not set the dataType as JSON.
Try to use below code which works well(Make sure the url is correct)
<div>
<label>Адресс</label>
<input class="form-control" id="AddressInput" type="text" placeholder="#ViewBag.User.Address" readonly /><br />
<button type="button" onclick ="AddressInputSet()"class="btn btn-primary" id="buttonSetAddress">Изменить</button>
<button type="button" onclick="SaveAddress()" class="btn btn-success" id="buttonSaveAddress" hidden>Сохранить</button>
</div>
#section Scripts{
<script type="text/javascript">
function AddressInputSet() {
document.getElementById('AddressInput').removeAttribute('readonly');
document.getElementById('buttonSetAddress').hidden = 'true';
document.getElementById('buttonSaveAddress').removeAttribute('hidden');
alert('sdfgdfg');
};
function SaveAddress() {
var data ={
userId: #ViewBag.User.Id,
address: document.getElementById('AddressInput').value
};
$.ajax({
type: 'POST',
url: '/Account/ResetAddress',
data: data,
//contentType: "application/x-www-form-urlencoded; charset=utf-8",
//dataType: JSON,
success: function () {
document.getElementById('buttonSaveAddress').hidden = 'true';
},
error: function () {
alert('Error');
}
});
};
</script>
}
Action:
[HttpPost]
public async void ResetAddress(string userId, string address)
try add quote to this value
var data = {
userId: '#ViewBag.User.Id', // here
address: document.getElementById('AddressInput').value
};
var data =JSON.stringify( {
userId: '#ViewBag.User.Id', // here
address: document.getElementById('AddressInput').value
});
You have to use JSON.stringify to turn you object to json.
and also yo must set content type in ajax

how to show the data from the get method by calling it from jquery ajax?

I am developing an online Hotel Management system in asp[dot]net mvc. I have a list of items and each item has a checkbox in it which is for adding it to the order list whenever it is to be added. Problem is whenever I click "Add To Orders" button I get "error alert". I want Get Method of order controller to be called so that data in it should be shown in the view. Also check whether my post method is right or not?
<div class="form-group">
<div class="col-md-offset-2 col-md-2">
<input value="Add to Orders" class="btn btn-primary" onclick="submitItems()" />
#*<input id="submit" value="Place an Order" class="btn btn- primary" onclick="" />*#
</div>
</div>
<script>
//$('#submit').on('click', function (e) {
// e.preventDefault();
var submitItems = function () {
var arrItems = [];
var commaSepratedValues = "";
$("#itemList input[type=checkbox]").each(function (index, val) {
debugger;
var checkedId = $(val).attr("id");
var arr = checkedId.split("_");
var currentItemId = arr[1];
var isChecked = $("#" + checkedId).is(":checked", true);
if (isChecked) {
arrItems.push(currentItemId);
}
})
if (arrItems.length != 0) {
commaSepratedValues = arrItems.toString();
$.ajax({
url: "/Order/Create",
type: "GET",
data: { ItemList: commaSepratedValues },
success: function (data) {
alert('success');
},
error: function () { alert('error'); }
});
}
}
</script>
Above is the code where my function executes and then the problem arises.
Main Menu
Step 1
Step 2
step 3

Sending simple type from HTML form to ASP API

I am having troubles with sending a simple double number from form to ASP API.
When I submit the form, I firstly need to remove Submit button to avoid sending a redundant 'submit=Submit' value to API controller.
As I have read in this article, I set the name of my input field to be empty. So if I check the http request in Developer mode, the body of sent data looks like so '=value'. My method parameter is decorated with [FromBody] attribute.
Even with all this, the controller method does not get the value. It is allways zero.
What to do?
My form looks like so:
<form action="#Url.Action("Temperature","Api")" method="post" >
<input type="number" name=" " step="0.25"/>
<input type="submit" name="submit" />
</form>
</div>
<script>
$("form").submit(function () {
$(this).children('[name="submit"]').remove();
});
</script>
The controller:
// POST: api/Temperature
public void Post([FromBody]double value) //FormDataCollection data
{
Temperature newEntry = new Temperature() { Timestamp = DateTime.Now, Value = value};
try
{
db.Temperatures.Add(newEntry);
db.SaveChanges();
}
catch(Exception e)
{
Debug.WriteLine(e.Message);
}
}
Try Ajax...
Change your Html little bit like this:
<div>
<input type="number" id="number" name=" " step="0.25"/>
<input type="button" id="submit" name="submit" />
</div>
Then:
$(document).on('click', '#submit', function () {
$.ajax({
type: 'POST',
url: '/ControllerName/Post',
data: {
value: JSON.stringify($('#number').val())
},
success: function (data) {
alert(data);
},
error: function (data) {
alert("An Issue has occured");
}
});
})
Also your controller input parameters would be like:
public void Post([FromBody]string value) //convert string to double later within method

Getting a local variable value using jQuery

I have a little problem when trying to get the value of a local int variable on a view, using jQuery. So, I have a the main view, and as you can see in the code below, I use a partial view named "_Result", when I try to get the value of indexPage by handling the click event of a button in the partial view, I get 0, event if I initialize my variable by another value(5 for example). Any idea why ?
Thanks in advance
My view :
#model System.Data.DataTable
#{var pageIndex = 5;}
<div>
<div>
<span>Téléphone ?</span>
<input id="idTxTel" type="text" name="txTelephone"/>
<input id="idBnSearch" type="submit" value="Chercher" name="bnSearch"/>
</div>
#Html.Partial("_Result", Model)
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#idBnSearch").click(function () {
//The right value (5)
alert('#pageIndex');
var telValue = $("#idTxTel").val();
var methodUrl = '#Url.Content("~/Search/GetReverseResult/")';
'#{pageIndex = 0;}'
doReverseSearch(telValue, '#pageIndex', methodUrl);
});
$("#bnNextPage").live("click", function ()
{
//Not th right value (0)
alert('#pageIndex');
});
});
</script>
My doReverseSearch method :
function doReverseSearch(telValue, pageIdx, methodUrl)
{
$.ajax(
{
url: methodUrl,
type: 'post',
data: JSON.stringify({ Telephone: telValue, pageIndex: pageIdx }),
datatype: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#result').replaceWith(data);
},
error: function (request, status, err) {
alert(status);
alert(err);
}
});
}
My partial view :
<div id="result">
<h2>Résultat de la recherche</h2>
<div>#ViewBag.CountResult entreprises trouvées</div>
#if(Model != null)
{
foreach (DataRow row in Model.Rows)
{
<h3>#row["CompanyName"]</h3>
}
}
<hr />
<div>
<span>Page N sur M</span>
<input id="bnPreviousPage" type="submit" value="Précédant" name="bnPrevious"/>
<input id="bnNextPage" type="submit" value="Suivant" name="bnNext"/>
</div>
</div>
Razor inside javascript has to be wrapped in a block
so you can do this:
<script>
// global value for page
<text>
var myPage = #pageIndex;
<text>
</script>
what would be far easier is give the button an attribute of data-page and ask for attribute in click event:
<button data-page="#("pageIndex")" id="myButt" />
$("#myButt").on("click",function(e){
var pageIndex = $(this).attr("data-page");
alert(pageIndex);
});

Categories