Set a static string if field is not empty [ASPNET MVC] - viewbag

I have this problem:
I have a result grid with a column named Note. I want to set a static string into the column cell (e.g: Nota) if note field is full (now in this field there is the note content) else I want to display a empty cell.
This is my Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CLI_POLIZZA cli_polizza)
{
if (ModelState.IsValid)
{
var cliPolizzaManager = new CliPolizzaManager();
cli_polizza.RegistrazioneID = Guid.NewGuid();
if (cli_polizza.Tipo =="C"){
cliPolizzaManager.GetScadenza(dataScadenza,
cli_polizza.GGAnticipo);
var dataScadenza = (DateTime)cli_polizza.DataScad;
cli_polizza.DataAvviso = dataScadenza.AddDays((-1) * (double)cli_polizza.GGAnticipo);
}
db.CLI_POLIZZA.Add(cli_polizza);
db.SaveChanges();
**if (cli_polizza.Nota != null)
{
TempData["Message"] = "Nota";
}**
return RedirectToAction("Index");
}
public ActionResult Index()
{
var cli_polizza = db.CLI_POLIZZA.Include(c => c.CLIENTE).Include(c => c.POLIZZA);
ViewBag.Message = TempData["Message"];
return View(cli_polizza.ToList());
}
This is my View:
<tbody>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.CLIENTE.FullName)
</td>
...
<td>
**#Html.DisplayFor(modelItem => #ViewBag.Message)**
</td>
<td>
<button type="button" class="btn btn-dark btn-sm">#Html.ActionLink("Modifica", "Edit", new { id = item.RegistrazioneID }) </button>
<button type="button" class="btn btn-success btn-sm">#Html.ActionLink("Dettaglio", "Details", new { id = item.RegistrazioneID }) </button>
<button type="button" class="btn btn-danger btn-sm">#Html.ActionLink("Cancella", "Delete", new { id = item.RegistrazioneID }) </button>
</td>
</tr>
I can't use viewbag with redirecttoaction so I tried to use Tempdata but with No result: I'm newbie
I would like to have following result:
Can someone help me?

Try this:
#Model.Note==null? “Note”: Model.Note

Related

data is not deleted after click on Delete Button in ASP.NET MVC

I created view where i listed my all records and i wanted to delete particular record after click on delete Button . But my record is deleted.
Following is the code-
Controller code-
public ActionResult Faqdelete()
{
var res = dbobj.tbl_FAQ.ToList();
return View(res);
}
[HttpPost]
public ActionResult Faqdelete(int id)
{
var res = dbobj.tbl_FAQ.Where(x => x.FAQ_ID == id).FirstOrDefault();
dbobj.tbl_FAQ.Remove(res);
dbobj.SaveChanges();
var Faqdata = dbobj.tbl_FAQ.ToList();
return View("Faqdelete",Faqdata);
}
- View page Code-
#model IEnumerable<ClassOne_SampleProject.Models.tbl_FAQ>
#{
ViewBag.Title = "Faqdelete";
}
<h2>Faqdelete</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.FAQ_Question_Answer)
</th>
<th>Action</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.Raw(item.FAQ_Question_Answer)
</td>
<td>
Delete
</td>
</tr>
}
</table>
Please tell me where exactly the problem.
Modify your anchor tag as
<td>
<a href="Url.Action("Faqdelete", "somecontroller", new { id = item.FAQ_ID })"
class="btn btn-danger">Delete</a>
</td>

I'm having trouble getting data from razor page

I have a controller where i call a page with a data model.
//** Get all members
IEnumerable<mdMedlemmer> medlemsModels = _medlemmer.GetAll(_options.LoggedInGuid.ToString());
//** Get listing result
var ListingResult = medlemsModels.Select(result => new MedlemsIndexListingModel
{
Id = result.ID,
Navn = result.Navn,
LicensNummer = result.LicensNummer,
Niveau = result.Niveau
}).OrderBy(o => o.Navn);
//** Set model
var model = new MedlemsIndexModel
{
Medlems = ListingResult
};
//** Show view with model
return View(model);
In my cshtml page i have this code:
#model MinDartklub.Models.Medlemmer.MedlemsIndexModel
<table class="table table-condensed" id="medlemsIndexTable">
<thead>
<tr>
<th>Navn</th>
<th>Vælg</th>
</tr>
</thead>
<tbody>
#using (Html.BeginForm("Pujle", "Turnering", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
int counter = 1;
#foreach (var medlems in Model.Medlems)
{
<tr class="medlemsRow">
<td class=""><input type="text" navn="txtSpiller_#counter" id="txtSpiller_#counter" value="#medlems.Navn" disabled/></td>
<td class=""><input type="checkbox" name="cbSpiller_#counter" /></td>
</tr>
counter++;
}
<tr class="medlemsRow">
<td class="" colspan="2"><input class="btn btn-lg btn-info" type="submit" value="Start pulje" /></td>
</tr>
}
</tbody>
</table>
Back in the controller i try to read the data:
[HttpPost]
public ActionResult Pujle(string txtSpiller_1, string cbSpiller_1)
{
return RedirectToAction("Index", "Turnering");
}
The cshtml pagge shows all the members and a checkbox
In the controller Start() method I want to read all the members who have been checked.
Any idea on how I do that?
I found out I could use Request.Form.ToList()
This gives me a list of the member where I clicked in the checkbox.

Passing value from model's property to #Html.RadioButtonFor() [duplicate]

I have a HTML table as below in my View:
<table id="tblCurrentYear">
<tr>
<td>Leave Type</td>
<td>Leave Taken</td>
<td>Leave Balance</td>
<td>Leave Total</td>
</tr>
#foreach (var item in Model.LeaveDetailsList)
{
<tr>
<td>#Html.TextBoxFor(m => item.LeaveType, new { width = "100" })</td>
<td>#Html.TextBoxFor(m => item.LeaveTaken, new { width = "100" })</td>
<td>#Html.TextBoxFor(m => item.LeaveBalance, new { width = "100" })</td>
<td>#Html.TextBoxFor(m => item.LeaveTotal, new { width = "100" })</td>
</tr>
}
</table>
I want to iterate through all the html table rows and insert the values in ADO.NET DataTable.
Simple speaking, converting HTML Table to ADO.NET DataTable.
How to extract values from HTML Table and insert into ADO.NET DataTable?
The view is based on the following model
public class LeaveBalanceViewModel
{
public LeaveBalanceViewModel()
{
this.EmployeeDetail = new EmployeeDetails();
this.LeaveBalanceDetail = new LeaveBalanceDetails();
this.LeaveDetailsList = new List<LeaveBalanceDetails>();
}
public EmployeeDetails EmployeeDetail { get; set; }
public LeaveBalanceDetails LeaveBalanceDetail { get; set; }
public List<LeaveBalanceDetails> LeaveDetailsList { get; set; }
}
In order to bind to a model on post back, the name attributes of the form controls must match the model properties. Your use of a foreach loop does not generate the correct name attributes. If you inspect the html you will see multiple instances of
<input type="text" name="item.LeaveType" .../>
but in order to bind to your model the controls would need to be
<input type="text" name="LeaveDetailsList[0].LeaveType" .../>
<input type="text" name="LeaveDetailsList[1].LeaveType" .../>
etc. The easiest way to think about this is to consider how you would access the value of a LeaveType property in C# code
var model = new LeaveBalanceViewModel();
// add some LeaveBalanceDetails instances to the LeaveDetailsList property, then access a value
var leaveType = model.LeaveDetailsList[0].LeaveType;
Since your POST method will have a parameter name (say model), just drop the prefix (model) and that's how the name attribute of the control must be. In order to do that you must use either a for loop (the collection must implement IList<T>)
for(int i = 0; i < Model.LeaveDetailsList.Count; i++)
{
#Html.TextBoxFor(m => m.LeaveDetailsList[i].LeaveType)
....
}
or use a custom EditorTemplate (the collection need only implement IEnumerable<T>)
In /Views/Shared/EditorTemplates/LeaveBalanceDetails.cshtml
#model yourAssembly.LeaveBalanceDetails
<tr>
<td>#Html.TextBoxFor(m => m.LeaveType)</td>
....
</tr>
and then in the main view (not in a loop)
<table>
.... // add headings (preferably in a thead element
<tbody>
#Html.EditorFor(m => m.LeaveDetailsList)
</tbody>
</table>
and finally, in the controller
public ActionResult Edit(LeaveBalanceViewModel model)
{
// iterate over model.LeaveDetailsList and save the items
}
With respect to your requirement, try this
jQuery(document).on("change", ".DDLChoices", function (e) {
var comma_ChoiceIds = '';
var comma_ChoicesText = '';
$('input[class="DDLChoices"]').each(function (e) {
if (this.checked) {
comma_ChoiceIds = comma_ChoiceIds + $(this).val() + ',';
comma_ChoicesText = comma_ChoicesText + $(this).parent('label').parent() + ',';
}
});
$('#ChoiceIds').val(comma_ChoiceIds);
$('#ChoiceText').val(comma_ChoicesText);
});
#using (Html.BeginForm("Actionname", "Controllername", FormMethod.Post, new { id = "frmChoices" }))
{
#Html.HiddenFor(m => m.ChoiceText, new { #id = "ChoiceText" })
#Html.HiddenFor(m => m.ChoiceIds, new { #id = "ChoiceIds" })
<div class="form-group">
<div>
<table>
<tr>
<th>Name</th>
<th>Selected</th>
</tr>
#foreach (var item in #Model.Choices)
{
<tr>
<td> <label>#item.ChoicesText</label> </td>
<td> <input class="DDLChoices" value="#item.ChoiceIds" type="checkbox" /></td>
</tr>
}
</table>
</div>
<input type="button" value="Submit" onclick="return ChoicesPoster.passChoices()"
</div>
}

ng-click dont work on list-group items button

I was searching for the solution, but can't resolve it.
I have HomeController and in its constructor I make some functions to work with firebase items. The list group displays todos and buttons, which are connected with data state. The code below shows the todo directive. I'm using scope to exchange the data.
ToDo App
Add Task
<!-- Task List Starts Here -->
<ul class="list-group" ng-show="!isLogged">
<li class="list-group-item clearfix message" ng-repeat="message in messages | filter: {mail : email}" ng-class="{disabled: ! message.done }">
<p class="lead">{{message.text}}</p>
<div>
<span class="pull-right">
<button class="btn btn-default btn-xs"><span class="glyphicon glyphicon-pencil"
ng-click="editTask(message)"></span></button>
<button class="btn btn-primary btn-xs" ng-show="! message.done"><span class="glyphicon glyphicon-ok" ng-click="doneTask(message)"></span></button>
<button class="btn btn-primary btn-xs" ng-show="message.done"><span class="glyphicon glyphicon-repeat" ng-click="unDoneTask(message)"></span></button>
<button class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove" ng-click="deleteTask(message)"></span></button>
</span>
</div>
</li>
</ul>
<!-- Task List Ends Here -->
</div>
And then I have main.controller file
export default class MainController {
constructor($scope, $firebaseArray, $firebaseAuth) {
var ref = new Firebase("https://learn11.firebaseio.com/todos");
$scope.messages = $firebaseArray(ref);
$scope.addMessage = function() {
$scope.messages.$add({
text: $scope.newMessageText
});
};
$scope.isLogged = false
$scope.loginUser = function() {
ref.authWithPassword({
email: $scope.email,
password: $scope.password
}, function(error, authData) {
if (error) {
$scope.isLogged = false
console.log("Login Failed!", error);
}
else {
$scope.isLogged = true
console.log($scope.isLogged)
}
});
};
$scope.addTask = function() {
var message_ref = new Firebase('https://learn11.firebaseio.com/todos');
var newMessageRef = message_ref.push();
newMessageRef.set({
'done': true,
'text': $scope.task,
'mail': $scope.email
});
};
$scope.editTask = function(message) {
$scope.task = $scope.messages[index].text;
console.log($scope.messages[index].text);
$scope.editIndex = index;
}
$scope.doneTask = function(message) {
$scope.messages[index].done = true;
}
$scope.unDoneTask = function(message) {
$scope.messages[index].done = false;
}
$scope.deleteTask = function(message) {
console.log(message)
$scope.messages.$remove(message)
}
}
}
Can you please help me? What can I do to make it work? And also do you know why isLogged state is not changed in view while it has changed in controller?
Try to use $scope.$apply(function () {$scope.isLogged = true}) for changing isLogged.

Passing an ID from Razor view to Controller

In a view of type List I'm trying to pass the id (which is an eMail in this case) of the item from the view to an actionResult in the controller: I used the following code():
#Html.ActionLink("Contact", "CreateMessage", "Member", new { id = item.eMail })
I get a null reference because the id passed is null.
Here's the view which works just fine and the id in it isn't null:
#model IEnumerable<Mutuelle.Domain.Entities.Adherent>
#{
ViewBag.Title = "lister";
}
<h2>Liste des adhérents</h2>
<table class="table">
<tr>
<body style="overflow:scroll;">
<th>
#Html.DisplayNameFor(model => model.dateOfBirth)
</th>
<th>
#Html.DisplayNameFor(model => model.address)
</th>
<th>
#Html.DisplayNameFor(model => model.phoneNumber)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.dateOfBirth)
</td>
<td>
#Html.DisplayFor(modelItem => item.address)
</td>
<td>
#Html.DisplayFor(modelItem => item.phoneNumber)
</td>
<td>
#Html.ActionLink("Contacter", "CreateMessage", "MembreComite", new { id = item.eMail })
</td>
</tr>
}
</table>
Here's the controller:
public ActionResult CreateMessage(string id)
{
Message message = new Message();
return View(message);
}
[HttpPost]
public ActionResult CreateMessage(Message message, string id)
{
if (ModelState.IsValid)
{
AMDMService service = new AMDMService();
Member member = service.GetMemberByeMail(id);
message.member = member;
message.adherentId = id;
member.listMessages.Add(message);
return RedirectToAction("listeMessages");
}
return View(message);
}
When you use routeValues like new { id = item.eMail } in your ActionLink, then you always should provide value for html attributes, which mostly used for styling your link, so if you don't want to style your link then you pass null otherwise you pass something like that new { #class = "btn btn-rounded btn-blue" }). So your code for ActionLink should look like this if you don't want to style your link:
#Html.ActionLink("Contact", "CreateMessage", "Member", new { id = item.eMail }, null);
Also you can replace #Html.ActionLink helper with #Url.Action helper like below:
Contact