MVC ActionLink image not displayed and data not passed - asp.net-mvc

I have the following ActionLink:
#if (ViewBag.Locality != null)
{
<h4>Active Localities:</h4>
<table class="table table-hover">
#foreach (var loc in ViewBag.Locality)
{
<tr>
<td>#loc.Locality</td>
<td>#Html.ActionLink(" ", "RemoveActive", new { #class = "removeBtn" }, new { id = #loc.Locality })</td>
</tr>
}
</table>
}
However, the class removeBtn is not being applied as below from the CSS:
a.removeBtn
{
background:url('http://news.techgenie.com/files/symbols-delete.png') no-repeat top left;
display: block;
background-size: 20px;
width: 50px;
height: 20px;
text-indent: -9999px;
}
Additionally, upon click the id is not being passed to the controller method, the parameter is being passed as null

You are using actionlink in a wrong way,here is the demonstration of proper actionlink usage:
Html.ActionLink(article.Title, <--Text of actionlink
"Item", <-- ActionMethod
"Login", <-- Controller Name.
new { article.ArticleID }, <-- Route arguments.
new { #class="btn" } <-- htmlArguments.
)
Ans for ur question is:
#Html.ActionLink("// Title //", "RemoveActive", "// Your controller Name //" ,new { id = #loc.Locality },new { #class = "removeBtn" })

Related

Knockout/Select2: problems getting dropdowns to work correctly for book transfer application

So I'm having trouble with my application that I'm trying to complete. It's supposed to send a list of changes I want for possessions of books. Right now I have a couple viewmodels in knockout that contains data that has been passed in through json.
I've been trying to get the dropdowns populated with the correct lists and track the changes that happen, but I'm not having any luck. This is the binding that I've been trying to use to attach the lists to the dropdowns. I am able to populate them but I cannot select anything.
function BookPossessionTransferVM() {
var self = this;
self.AllFromList = ([
{"IsAdult":false,"Name":"Bob","ID":38438},
{"IsAdult":false,"Name":"Gordon","ID":54686}
]);
self.PossessionChanges = ko.observableArray([]);
self.PossessionChanges.push(new PossessionChangeModel());
self.AvailableFrom = ko.computed(function() {
var possessionChangesValues = self.PossessionChanges(),
available = ko.utils.arrayFilter(self.AllFromList, function(selectedPerson) {
return !ko.utils.arrayFirst(possessionChangesValues , function (possessionChange) {
if (possessionChange.SelectedFrom() !== undefined) {
return possessionChange!= self &&
possessionChange.SelectedFrom().Name() === selectedPerson.Name;
} else {
return false;
}});
});
return available;
});
self.AvailableTo = ko.computed(function() {
var possessionChangesValues = self.PossessionChanges(),
available = ko.utils.arrayFilter(self.AllToList, function(selectedPerson) {
return !ko.utils.arrayFirst(possessionChangesValues , function (possessionChange) {
if (possessionChange.SelectedFrom() !== undefined) {
return possessionChange!= self &&
possessionChange.SelectedFrom().Name() === selectedPerson.Name;
} else {
return false;
}});
});
return available;
});
self.addPossessionChange = function () {
self.PossessionChanges.push(new PossessionChangeModel());
}
self.removePossessionChangeChange = function(possessionChange) {
self.PossessionChanges.remove(possessionChange);
}
}
function PossessionChangeModel() {
var self = this;
self.SelectedFrom = ko.observable(new SelectedPerson());
self.SelectedTo = ko.observable(new SelectedPerson());
self.ChangeType = ko.pureComputed(function() {
if (self.SelectedFrom() !== undefined && self.SelectedTo() !== undefined) {
return 'Update';
} else if (self.SelectedFrom() === undefined && self.SelectedTo() === undefined) {
return '';
} else if (self.SelectedFrom() === undefined) {
return 'Add';
} else if (self.SelectedTo() === undefined) {
return 'Remove';
} else { return ''; }
});
}
function SelectedPerson() {
var self = this;
self.IsAdult = ko.observable(false);
self.Name = ko.observable("None");
self.ID = ko.observable(0);
}
ko.bindingHandlers.select2 = {
init: function (element, valueAccessor, allBindingsAccessor, bindingContext) {
ko.utils.domNodeDisposal.addDisposeCallback(element,
function() {
$(element).select2('destroy');
});
var select2 = ko.utils.unwrapObservable(allBindingsAccessor().options);
$(element).select2(select2);
},
update: function (element, valueAccessor, allBindingsAccessor, bindingContext) {
var allBindings = allBindingsAccessor();
if ("value" in allBindings) {
if ((allBindings.select2.multiple || element.multiple) && allBindings.value().constructor != Array) {
$(element).val(allBindings.value().split(',')).trigger('change');
} else {
$(element).on('select2:selecting', function(e) {
var data = e.params.args.data.id;
console.log(data);
});
$(element).val(allBindings.value()).trigger('change');
}
}
$(element).trigger("change");
}
};
ko.applyBindings(new BookPossessionTransferVM());
#tblPossessionChanges {
width: 70%;
height: 100px;
text-align: center;
table-layout: fixed;
}
#tblReassignChanges td, #tblPossessionChanges th {
padding: 1rem;
}
#tblReassignChanges thead th {
text-align: center;
}
#tblReassignChanges thead th:first-child {
text-align: left;
width: 10%;
}
#tblReassignChanges tbody td:first-child {
text-align: left;
width: 10%;
}
#tblReassignChanges > tbody > tr > td.prompt > a{
font-weight: bold;
}
#tblReassignChanges tbody td select{
width: 75%
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/js/select2.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/css/select2.min.css" />
<div>
<table id="tblReassignChanges">
<thead>
<tr>
<th>Add</th>
<th>From</th>
<th>To</th>
</tr>
</thead>
<tbody data-bind="foreach: PossessionChanges">
<tr>
<td class="prompt">
Delete </td>
<td>
<select class="form-control"
data-bind="options: $root.AvailableFrom,
value: SelectedFrom,
optionsText: 'Name',
optionsValue: 'ID',
select2: { placeholder: 'Please select a Person...', allowClear: true}"> </select>
</td>
<td>
<select class="form-control"
data-bind="options: $root.AvailableTo,
value: SelectedTo,
optionsText: 'Name',
optionsValue: 'ID',
select2: {placeholder: 'Please select a Person...', allowClear: true}"> </select>
</td>
<td>
<span id="changeTypeSpan" data-bind="text: ChangeType"></span>
</td>
</tr>
</tbody>
</table>
</div>
I've also tried changing the optionsValue to use the ID but then that overrides the selectedPerson objects that I have. I am open to all suggestions and help. Thank you!
EDIT: Here is the jsFiddle that replicates my issue and so that it saves space. I hard coded in data as well. https://jsfiddle.net/3upb0mf8/5/
You've got multiple problems here:
The main issue is that you assume that possessionChange.SelectedFrom() contains the entire person object, while actually it only contains its id, because that's what's passed to optionsValue. Please read this answer to fully understand it. You must retrieve the person by its id.
AvailableTo refers to possessionChange.SelectedFrom() instead of possessionChange.SelectedTo().
name conflict: removePossessionChange vs removePossessionChangeChange.
A PossesionChange must have an id so it can be deleted.
And few other problems.
I think I fixed most of the problems. Also note I'm using a PersonVM instead of plain objects:
function BookPossessionTransferVM() {
var self = this;
self.All = [new PersonVM(false,"Bob",38438), new PersonVM(false,"Gordon",54686)];
self.PossessionChanges = ko.observableArray([]);
self.AvailableFrom = ko.computed(function() {
var available = ko.utils.arrayFilter(self.All, function(item) {
return !ko.utils.arrayFirst(self.PossessionChanges() , function (possessionChange) {
var person = self.getPersonById(possessionChange.SelectedFrom());
if (person) {
return person.Name() === item.Name();
} else {
return false;
}
});
});
return available;
});
self.AvailableTo = ko.computed(function() {
var available = ko.utils.arrayFilter(self.All, function(item) {
return !ko.utils.arrayFirst(self.PossessionChanges() , function (possessionChange) {
var person = self.getPersonById(possessionChange.SelectedTo());
if (person) {
return person.Name() === item.Name();
} else {
return false;
}});
});
return available;
});
self.getPersonById = function (id) {
return ko.utils.arrayFirst(self.All, function(person){
return person.ID === id;
});
}
self.addPossessionChange = function () {
self.PossessionChanges.push(new PossessionChangeVM(self.PossessionChanges.length + 1));
}
self.removePossessionChange = function(possesion) {
self.PossessionChanges.remove(function (item) {
return possesion.possesionId() == item.possesionId();
});
}
}
function PossessionChangeVM(possesionId) {
var self = this;
self.possesionId = ko.observable(possesionId);
self.SelectedFrom = ko.observable();
self.SelectedTo = ko.observable();
self.ChangeType = ko.pureComputed(function() {
if (self.SelectedFrom() !== undefined && self.SelectedTo() !== undefined) {
return 'Update';
} else if (self.SelectedFrom() === undefined && self.SelectedTo() === undefined) {
return '';
} else if (self.SelectedFrom() === undefined) {
return 'Add';
} else if (self.SelectedTo() === undefined) {
return 'Remove';
} else { return ''; }
});
}
function PersonVM(isAdult, name, id) {
var self = this;
self.IsAdult = ko.observable(isAdult);
self.Name = ko.observable(name);
self.ID = ko.observable(id);
}
ko.bindingHandlers.select2 = {
init: function (element, valueAccessor, allBindingsAccessor, bindingContext) {
ko.utils.domNodeDisposal.addDisposeCallback(element,
function() {
$(element).select2('destroy');
});
var select2 = ko.utils.unwrapObservable(allBindingsAccessor().options);
$(element).select2(select2);
},
update: function (element, valueAccessor, allBindingsAccessor, bindingContext) {
var allBindings = allBindingsAccessor();
if ("value" in allBindings) {
if ((allBindings.select2.multiple || element.multiple) && allBindings.value().constructor != Array) {
$(element).val(allBindings.value().split(',')).trigger('change');
} else {
$(element).on('select2:selecting', function(e) {
var data = e.params.args.data.id;
});
$(element).val(allBindings.value()).trigger('change');
}
}
$(element).trigger("change");
}
};
ko.applyBindings(new BookPossessionTransferVM());
#tblPossessionChanges {
width: 70%;
height: 100px;
text-align: center;
table-layout: fixed;
}
#tblReassignChanges td, #tblPossessionChanges th {
padding: 1rem;
}
#tblReassignChanges thead th {
text-align: center;
}
#tblReassignChanges thead th:first-child {
text-align: left;
width: 10%;
}
#tblReassignChanges tbody td:first-child {
text-align: left;
width: 10%;
}
#tblReassignChanges > tbody > tr > td.prompt > a{
font-weight: bold;
}
#tblReassignChanges tbody td select{
width: 75%
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/js/select2.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/css/select2.min.css" />
<div>
<table id="tblReassignChanges">
<thead>
<tr>
<th>Add</th>
<th>From</th>
<th>To</th>
</tr>
</thead>
<tbody data-bind="foreach: PossessionChanges">
<tr>
<td class="prompt">
Delete </td>
<td>
<select class="form-control"
data-bind="options: $root.AvailableFrom,
value: SelectedFrom,
optionsText: 'Name',
optionsValue: 'ID',
select2: { placeholder: 'Please select a Person...', allowClear: true}"> </select>
</td>
<td>
<select class="form-control"
data-bind="options: $root.AvailableTo,
value: SelectedTo,
optionsText: 'Name',
optionsValue: 'ID',
select2: {placeholder: 'Please select a Person...', allowClear: true}"> </select>
</td>
<td>
<span id="changeTypeSpan" data-bind="text: ChangeType"></span>
</td>
</tr>
</tbody>
</table>
</div>

asp.net core page not found

I have error "Page not found" on my website.
This is what i have came up with.
Error occurred to clients few times without me knowing exact moment
When i tested it it ALWAYS happens when i restart my website asp.net server but under some circumstances which i will describe later
It happens in some controllers but in some not
It happens only until i open some controller that will load website, then all other works too.
It happens only on published website and not in my local environment.
So first line is clear and doesn't need explanation.
Second line:
What i have tested to get this error is i shut down my server and then start it again. After it i try going to mywebsite.com/User and error comes.
Third line:
It only happens in controllers /User and /Kalkulator but not in / or /Proizvodi
Forth line:
When i open controller /User and refresh it multiple times it doesn't load but when i go to / and then to /User it loads.
Here are my controllers with their views. I will only provide /User and /Kalkulator since there is easiest to see what happens.
public class UserController : Controller
{
public IActionResult Index()
{
//Debug log are control lines that write to my txt file but they are never reached on first time going to this controller, but when i do fourth step they do reach.
Debug.Log(null, "User/Index pocetak", Debug.Type.CasualChange, Request);
try
{
Debug.Log(null, "User/Index Checking isLogged", Debug.Type.CasualChange, Request);
if (Networking.IsLogged(Request))
{
Debug.Log(null, "User/Index Checking isAdmin", Debug.Type.CasualChange, Request);
if (Networking.IsAdmin(Request))
{
Debug.Log(null, "User/Index Return redirect admin", Debug.Type.CasualChange, Request);
return Redirect("/Admin?select=POR");
}
else
{
Debug.Log(null, "User/Index Return redirect /Proizvodi", Debug.Type.CasualChange, Request);
return Redirect("/Proizvodi");
}
}
Debug.Log(null, "User/Index Creting new user class", Debug.Type.CasualChange, Request);
AR.TDShop.User u = new AR.TDShop.User();
Debug.Log(null, "User/Index Return view with user class", Debug.Type.CasualChange, Request);
return View(u);
}
catch (Exception ex)
{
Debug.Log(null, "User/Index catch error", Debug.Type.CasualChange, Request);
return View("Error", ex.ToString());
}
}
User View
#model AR.TDShop.User
#{
ViewData["Title"] = "Profi kutak";
}
<style>
#Login {
margin: auto;
position: relative;
width: 400px;
text-align: center;
margin-top: 100px;
border-radius: 10px;
border: 1px solid red;
}
#Login input {
margin-top: 10px;
text-align: center;
height: 40px;
font-size: 30px;
width: 60%;
}
#Login button {
margin-top: 20px;
margin-bottom: 20px;
width: 200px;
height: 40px;
font-size: 18px;
border: none;
background-color: #ff0000;
border-radius: 0px 0px 20px 20px;
color: white;
font-weight: bolder;
}
#Login button:hover {
background-color: #ff4d4d;
}
#PostaniClan button:hover {
background-color: lawngreen !important;
color: black !important;
}
</style>
#using (Html.BeginForm("Login", "User", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div id="Login">
<p style="padding-top: 10px; padding-bottom: 10px; border-radius: 10px 10px 0 0; color: white; background-color: red; font-weight: bolder; font-size: x-large">Logovanje</p>
#Html.TextBoxFor(x => x.Name, new { #placeholder = "username" })
<br />
#Html.TextBoxFor(x => x.PW, new { #placeholder = "password", #type = "password" })
<br />
<button type="submit">Potvrdi</button>
</div>
}
<div style="text-align: center; margin-top: 30px; margin-bottom: 30px" id="PostaniClan">
<button onclick="window.location.href='/Majstori/Registracija'" style="background-color: green; color: white; border-radius: 20px; padding: 10px 20px 10px 20px;">Postani član!</button>
</div>
}
As you can see in user controller/view there are few other commands that are not shown here but i think you do not need them and you will get it when you take a look at /Kalkulator controller which also doesn't works and here it is:
public class KalkulatorController : Controller
{
public IActionResult Index()
{
return View();
}
}
and here is the view:
#{
ViewData["Title"] = "Kalkulator";
}
<div class="main-wrapper">
<div class="card bg-info text-center" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">GKP - Plafon</h5>
<p class="card-text">Izracunajte utrosak materijala koji Vam je potreban za izradu spustenog plafona u gips karton sistemu.</p>
Izracunaj!
</div>
</div>
<div class="card bg-info text-center" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">GKP - Zid (oblaganje)</h5>
<p class="card-text">Izracunajte utrosak materijala koji Vam je potreban za oblaganje postojeceg zida.</p>
Izracunaj!
</div>
</div>
<div class="card bg-info text-center" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">GKP - Zid (pregradjivanje)</h5>
<p class="card-text">Izracunajte utrosak materijala koji Vam je potreban za izradu novog pregradnog zida.</p>
Izracunaj!
</div>
</div>
</div>
As you can see it is pure HTML and it doesn't work....
Here is my /Proizvodi controller which works (it has a lot of commands so i will display only index and view)
public IActionResult Index(int? GrupaID, int? PodgrupaID, int? V, string Pretraga)
{
ProizvodiModel pm = new ProizvodiModel(GrupaID, PodgrupaID, V, Request);
pm.Tag = Pretraga;
return View(pm);
}
VIEW:
#model ProizvodiModel
#{
ViewData["Title"] = "Proizvodi";
List<Tuple<int, double>> CeneZaKorisnika = new List<Tuple<int, double>>();
if (Networking.IsLogged(Context.Request))
{
CeneZaKorisnika = AR.TDShop.User.GetVPCene(Model.User.UserID);
CeneZaKorisnika.Sort((x, y) => x.Item1.CompareTo(y.Item1));
}
if (!Model.Majstor)
{
<style>
.proizvod {
margin-bottom: 5px !important;
}
</style>
}
else
{
<style>
.proizvod {
margin-bottom: 103px !important;
}
</style>
}
}
<link rel="stylesheet" type="text/css" href="~/css/ProizvodiIndex.css" />
<div class="main-wrapper">
<div id="left" class="col-sm-3" style=" color: white">
<div style="width: 100%; margin-top: 40px; margin-bottom: 40px; text-align: center">
<img src="~/images/Logo_Long.png" style="width: 90%;" />
</div>
#if (Model.Majstor)
{
Model.User.UcitajPorudzbine(Context.Request);
if (Model.User.Porudzbine.Count > 0)
{
<div style="background-color: red; margin-top: 10px; padding-top: 10px; padding-bottom: 10px">
<h3 style="text-align: center; margin: 0;">Skorašnje porudžbine</h3>
#{
int n = 5;
<table id="PorudzbineTable" style="width: 100%;margin-top: 10px; background-color: #ffbbbb; color: black">
#foreach (AR.TDShop.Porudzbina p in Model.User.Porudzbine)
{
<tr onclick="window.location.href='/Porudzbina?ID=' + #p.PorudzbinaID">
<td style="padding-left: 10px">#p.BrDokKom</td>
#switch (p.Status)
{
case AR.TDShop.Porudzbina.PorudzbinaStatus.NaObradi:
<td>Na obradi!</td>
break;
case AR.TDShop.Porudzbina.PorudzbinaStatus.CekaUplatu:
<td>Čeka uplatu!</td>
break;
case AR.TDShop.Porudzbina.PorudzbinaStatus.ZaPreuzimanje:
<td>Za preuzimanje!</td>
break;
case AR.TDShop.Porudzbina.PorudzbinaStatus.Preuzeto:
<td>Realizovano!</td>
break;
case AR.TDShop.Porudzbina.PorudzbinaStatus.Stornirana:
<td>Stornirano!</td>
break;
}
</tr>
n--;
if (n <= 0)
{
break;
}
}
</table>
<button id="SvePorudzbine" onclick="window.location.href='/User/Porudzbine'" style="text-align: center; margin-top: 10px; background-color: white; color: black">Sve porudzbine</button>
}
</div>
}
<div id="ObjasnjenjeCene">
<p>Cena bez PDV-a je iskazana crvenom bojom!</p>
</div>
}
<div style="padding: 15px; background-color: #5a5cd4; margin-bottom: 40px">
<button class="#if (#Model.ActivateGrupa == null && Model.ActivatePodgrupa == null) { #Html.Raw("activate") }" onclick="GoTo('/Proizvodi')">Svi proizvodi</button>
#foreach (GrupaModel g in Model.Grupe)
{
<button class="#if (Model.ActivateGrupa != null && Model.ActivateGrupa == g.GrupaID)
{
#Html.Raw("activate")
} else if (#Model.ActivatePodgrupa != null)
{
if(PodgrupaModel.GetParent((int)Model.ActivatePodgrupa) == g.GrupaID) { #Html.Raw("activate") }
}"
onclick="GoTo('/Proizvodi?GrupaID=#g.GrupaID')">
#g.Naziv
</button>
}
</div>
<div id="PredloziProizvod" style="border-top: black 2px; color: black;">
<button id="predloziButton" style="width: 100%; text-align: center">Predloži proizvod</button>
<input hidden type="text" placeholder="Naziv proizvoda" />
<input hidden type="text" placeholder="Kataloski broj" />
<input hidden type="text" placeholder="Opis primene" />
<button hidden id="PosaljiPredlogProizvoda">Posalji</button>
</div>
</div>
<div id="right" class="col-sm-9">
<div id="PretragaProizvoda">
<input type="text" placeholder="Pretraga..." value="#Model.Tag" />
<button id="tw" style="float: right" onclick="ToggleView(this)" value="0"><img src="~/images/View2.png" style="width: 25px" /></button>
</div>
<br />
#if (Model.PodGrupe.Count > 0)
{
string cls = "";
if (Model.ActivatePodgrupa == null)
{
cls = "aktivnaPodgrupa";
}
<div id="PodGrupe">
<button class="PodGrupa #cls" onclick="GoTo('/Proizvodi?GrupaID=#PodgrupaModel.GetParent((int)Model.PodGrupe[0].PodgrupaID))'">
<p>Svi proizvodi grupe</p>
</button>
#foreach (PodgrupaModel pgm in Model.PodGrupe)
{
cls = "";
if (pgm.PodgrupaID == Model.ActivatePodgrupa)
{
cls = "aktivnaPodgrupa";
}
<button class="PodGrupa #cls" onclick="GoTo('/Proizvodi?PodgrupaID=#pgm.PodgrupaID')">
<p>#pgm.Naziv</p>
</button>
}
</div>
<hr style="border-bottom: 2px solid black" />
}
#foreach (ProizvodModel p in Model.Proizvodi)
{
if (p.Aktivan)
{
string proizvodStil;
string buttonStil;
if (p.Klasifikacija == 0)
{
proizvodStil = "color: dimgray;";
buttonStil = "background: linear-gradient(to bottom, white, dimgray 20%, dimgray 80%, white 100%);";
}
else if (p.Klasifikacija == 2)
{
proizvodStil = "color: darkorange;";
buttonStil = "background: linear-gradient(to bottom, white, darkorange 20%, darkorange 80%, white 100%);";
}
else
{
proizvodStil = "color: darkgreen;";
buttonStil = "background: linear-gradient(to bottom, white, darkgreen 20%, darkgreen 80%, white 100%);";
}
<div class="proizvod ppppp #if (Model.Majstor) { #Html.Raw("korpa"); } normal"
#Html.Raw("onclick = \"GoToP('" + #p.ROBAID + "')\"") ;
style="#proizvodStil">
<p class="katBr">#p.KatBr</p>
<img src="#p.Slika" />
<p class="nazivProizvoda">#p.Naziv</p>
#if (Model.Majstor)
{
try
{
int NivoZaKorisnika = Model.User.Cenovnik_grupa.Where(x => x.Item1 == p.Cenovnik_GrupaID).Select(t => t.Item2).FirstOrDefault();
double VPCena = CeneZaKorisnika.Where(x => x.Item1 == p.ROBAID).FirstOrDefault().Item2;
double MPCena = VPCena + (VPCena * p.PDV / 100);
if (MPCena > 0)
{
<p class="vpcena">#VPCena.ToString("#,###.00") / #p.JM</p>
<p class="mpcena">#MPCena.ToString("#,###.00") / #p.JM</p>
if (Model.User.Vrsta == UserModel.Tip.Majstor)
{
<button style="#buttonStil" onclick="GoToP(#p.ROBAID); event.stopPropagation();"> KUPI!</button>
}
}
if (Model.User.Vrsta == UserModel.Tip.Administrator)
{
<button style="#buttonStil" onclick="Edit(#p.ROBAID); event.stopPropagation();">Detalji!</button>
}
}
catch (Exception ex)
{
#:alert("#ex.ToString()");
}
}
</div>
}
}
</div>
</div>
<div id="AlertPopUp">
</div>
<script src="~/js/AlertBox.js"></script>
<script>
var alb = new AlertBox($("#AlertPopUp"));
var currRID = -1;
var overwrite = false;
function GoTo(link) {
if ($("#tw").val() == 1) {
if (link.indexOf('?') > -1) {
window.location.href = link + "&V=1";
}
else {
window.location.href = link + "?V=1";
}
}
else {
window.location.href = link;
}
}
function GoToP(link) {
if ($("#tw").val() == 1) {
if (link.indexOf('?') > -1) {
window.location.href = link + "&V=1";
}
else {
window.location.href = link + "?V=1";
}
}
else {
window.location.href = "/Proizvod?ID=" + link;
}
}
function Edit(id) {
GoTo("/Proizvodi/Edit?ID=" + id);
}
function ToggleView(element) {
var curr = $(element).val();
if (curr == 1) {
$(element).val(0);
$(element).children("img").attr("src", "/images/View2.png");
$(".ppppp").removeClass("proizvod1");
$(".ppppp").addClass("block");
$(".ppppp").addClass("proizvod");
$(".korpa button").html("Dodaj u korpu!");
}
else {
$(element).val(1);
$(element).children("img").attr("src", "/images/View1.png");
$(".ppppp").removeClass("proizvod");
$(".ppppp").removeClass("block");
$(".ppppp").addClass("proizvod1");
$(".korpa button").html("<img src='/Images/cart.png' style='height: 50px;width: 50px;border-radius: 10px;padding: 5px;padding-right: 8px;background-color: #2196F3;' />");
}
}
#{
if(Model.View == 1)
{
#:StartOtherView();
}
}
function StartOtherView() {
$("#tw").val(1);
$("#tw").children("img").attr("src", "/images/View1.png");
$(".ppppp").removeClass("proizvod");
$(".ppppp").removeClass("block");
$(".ppppp").addClass("proizvod1");
$(".korpa button").html("<img src='/Images/cart.png' style='height: 50px;width: 50px;border-radius: 10px;padding: 5px;padding-right: 8px;background-color: #2196F3;' />");
}
$(function () {
var PredloziProizvodBlock = false;
$("#predloziButton").click(function () {
$(this).parent().children("input").each(function () {
if (PredloziProizvodBlock == true) {
$(this).hide();
}
else {
$(this).show();
}
});
if (PredloziProizvodBlock == true) {
$("#PosaljiPredlogProizvoda").hide();
}
else {
$("#PosaljiPredlogProizvoda").show();
}
PredloziProizvodBlock = !PredloziProizvodBlock;
})
$("#PosaljiPredlogProizvoda").click(function () {
$.ajax({
type: "GET",
url: "/Proizvodi/PosaljiPredlogProizvoda",
contentType: "application.json; charset-utf-8",
dataType: "json",
async: false,
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
});
})
$("#PretragaProizvoda input").keyup(function () {
var input = $(this).val().toUpperCase();
$(".proizvod").each(function () {
if ($(this).html().toUpperCase().indexOf(input) >= 0 || input.length == 0) {
$(this).show();
}
else {
$(this).hide();
}
});
});
});
</script>
All views use same layout.
Routing option:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
I think your problem with Redirect in you UserController, could your try replace it on RedirectToAction(); It's must be help you.
I found out mistake and it was so easy.
I thought i was checking all my code which is ran when entering some page but i forgot one big part and it is constructor:
private readonly IHostingEnvironment hostingEnvironment;
public ProizvodiController(IHostingEnvironment he)
{
hostingEnvironment = he;
Program.AbsolutePath = hostingEnvironment.WebRootPath;
Debug.FilePath = Path.Combine(Program.AbsolutePath, "Log");
}
public IActionResult Index(int? GrupaID, int? PodgrupaID, int? V, string Pretraga)
{
ProizvodiModel pm = new ProizvodiModel(GrupaID, PodgrupaID, V, Request);
pm.Tag = Pretraga;
return View(pm);
}
I forgot that constructor is accessed each time when you access any page from controller and it sets my AbsolutePath variable which i use later.
When i restart my server he lose all in memory data (which is static variable AbsolutePath) and it is only set when ANY user enter website but since i call it only in 2 controllers, other controllers were not working.
Solution was to add same code to all controllers constructors.

Image's styles are ignored by iTextSharp

image inside .cshtml file:
<img src="~/Content/images/imghead.png" style=" border:4px solid #ffffff; border-radius:10px; box-shadow: 2px 2px #f2f2f2; "/>
This is how it's supposed to be:
This is how it looks:
EDIT:
The row below produces the first image (rounded corners) upthere on the HTML output. On pdf output looks like second image.
Styles are not cared.
<tr>
<td align="center" style=" height:120px; ">
<img src="https://abcstorage.blob.core.windows.net/Images/head.png" style="border:4px solid #ffffff; border-radius:10px; box-shadow: 2px 2px #f2f2f2; " />
</td>
</tr>
This is the Render() Method:
using (var pdfDocument = new Document(PageSize.A3, HorizontalMargin, HorizontalMargin, 110, 30))
{
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream);
pdfWriter.CloseStream = false;
pdfWriter.PageEvent = new PrintHeaderFooter();
pdfDocument.Open();
using (var htmlViewReader = new StringReader())
{
XMLWorkerHelper.GetInstance().ParseXHtml(pdfWriter, pdfDocument, htmlViewReader);
}
}
This is not how MVC work, the way you are doing it are more Asp .net Webform style.
Use css for this, or if you need dynamic change it use ViewBag such as (not tested):
Action
public ActionResult pdfOutput(string id, string pid)
{
ViewBag.ImgHeadBorder=iTextSharp.text.Rectangle.BOX;
}
View
#if(ViewBag.ImgHeadBorder != null)
{
<img id="imgHead" src="~/Content/images/imghead.png" style="border:#ViewBag.ImgHeadBorder"/>
}

How to achieve edit and delete on Webgrid of MVC3 Razor?

Below I have given the controller, model and view. After run, grid is displaying with values, but I need to edit the values and delete the values on same page. I have searched and seen some example, in that for edit, delete they creating separate index but mine need is to edit and delete should done on same page instead of another page. Please give me a solution.
Controller:
public ActionResult Index()
{
var PersonList = new List<Person>()
{
new Person(){Name="A", Age=20,Id =1},
new Person(){Name="B",Age=45,Id =2},
new Person(){Name="C", Age=30,Id =3},
new Person(){Name="D",Age=55,Id =4},
new Person(){Name="E", Age=30,Id =5},
new Person(){Name="F",Age=25,Id =6},
new Person(){Name="G", Age=30,Id =7},
new Person(){Name="H",Age=25,Id =8},
};
return View(PersonList);
}
Class :
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
View :
#model IEnumerable<edit.Models.Person>
#{
ViewBag.Title = "Index";
}
<html>
<head>
<title>Index</title>
<style type="text/css">
.webGrid { margin: 4px; border-collapse: collapse; width: 300px; }
.header { background-color: #E8E8E8; font-weight: bold; color: #FFF; }
.webGrid th, .webGrid td { border: 1px solid #C0C0C0; padding: 5px; }
.alt { background-color: #E8E8E8; color: #000; }
.person { width: 200px; font-weight:bold;}
</style>
</head>
<body>
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5);
grid.Pager(WebGridPagerModes.NextPrevious);
#grid.GetHtml(tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Name", "Given Name", canSort: true, format:#<b>#item.Name</b>, style: "person"),
grid.Column("Age", "How Old?", canSort: true)
));
}
</body>
</html>
#Yasser, it is very dangerous to implement a DELETE via a GET link. A search engine crawling the page might delete all your information.
It is much better to implement a POST operation. Here is an example:
In the View:
#functions{
string Delete(dynamic p)
{
string actionController = Url.Action("Delete", "Admin", new {id=p.AccountId});
return "<form style='display:inline;' method='post' action='" + actionController + "'><input type='submit' value='Delete' onclick=\"return confirm('Are you sure?')\"/></form>";
}
}
...
grid.Column(header: "", format: p => Html.Raw(Delete(p)))
In the Controller:
[HttpPost]
public ActionResult Delete(int id)
{
PerformDelete(id);
return RedirectToAction("Index");
}
Here is something you can start with,
You will have to first generate two action link called "Edit" and "Delete" along with each record in the webgrid.
See this tutorial for that.
something like this
grid.Column(format: (item) => Html.ActionLink("Edit", "ActionName", new { param1 = "send id here", param2 = "xtra param" }))
grid.Column(format: (item) => Html.ActionLink("Delete", "ActionName2", new { param1 = "hello", param2 = "bye" }))
Hope this helps.
Here you go...
http://www.dotnet-tricks.com/Tutorial/mvc/E2S9150113-Enhancing-WebGrid-with-Insert-Update-and-Delete-Operations.html
I think you are looking for this.
You can try this inline editable gridview using asp.net mvc and knockoutjs:
www.anhbui.net/blog?id=kojs-1

clear textbox text before ajax form submit event

I want to clear textbox after ajax posting.
<div style="padding: 5px; background-color: Silver;">
#using (Ajax.BeginForm("_MessagesPartial", "Chat", new AjaxOptions { UpdateTargetId = Model.room_id.ToString() }))
{
<div style="padding: 5px 15px 5px 5px;">
#Html.TextBox("textbox_message", null, new { #class = "text_yorum", id = "text_box_chat" })
#Html.Hidden("oda_id", Model.room_id)
</div>
}
</div>
<div id="#Model.room_id" style="height:400px;overflow-y:scroll;position: relative;">
#Html.Action("_MessagesPartial", "Chat", new { room_id = Model.room_id })
</div>
there are a lot of example, but they do not work.
I m already using this code, but it is too slow.
$("form").submit(function () {
$.get('#Url.Action("_MessagesPartial", "Chat", new { room_id = Model.room_id }) ', {}, function (view) {
$("##Model.room_id").html(view);
$("#text_box_chat").val("");
});
});
Is there any way to do this.
How about clearing the box before waiting for the response?
$("form").submit(function () {
setTimeout(function(){
$("#text_box_chat").val("");
}, 20);
$.get('#Url.Action("_MessagesPartial", "Chat", new { room_id = Model.room_id }) ', {}, function (view) {
$("##Model.room_id").html(view);
});
});

Resources