MVC: Display an input if two rows match in database using LINQ - asp.net-mvc

I am trying to hide that input if in database current logged user have already a Job posted on website, if UserID doesn't have anything added in database I want that input to be displayed/
At this point in View is displayed only that '< span >' no matter what.
#{
var db = new JobSite3.Models.ApplicationDbContext();
var controller = new JobSite3.Controllers.BaseController();
}
#if (db.Jobs.Where(x => x.UserID == controller.LoggedUserId).Select(x => x.ID) != null)
{
<span>No input</span>
}
else
{
<div class="form-group">
<div class="col-md-offset-1 col-md-10">
<input type="submit" value="Create" class="btn btn-default"/>
</div>
</div>
}

As per Stephen Muecke suggestions I made my code work and here is the solution in case someone needs too:
Controller:
// GET: Jobs/Create
public ActionResult Create()
{
var query = db.Jobs.Where(x => x.UserID == LoggedUserId).Select(x => x.ID.ToString()).Any();
ViewBag.HasJobs = query;
return View();
}
View:
#if (ViewBag.HasJobs != true)
{
<div class="form-group">
<div class="col-md-offset-1 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
else
{
<div class="form-group">
<div class="col-md-offset-1 col-md-10">
<input type="submit" value="Create" class="btn btn-default" disabled="disabled" />
</div>
</div>
}
There isn't anymore a < span > but the last input have a disabled parameter, which was the first intention.

Related

Edit action has not been hitting while I push the submit button

I have an edit button in each row of my Datatable. I have two actions for editing. One for Getting data in a Datatable and the other one for posting my information. The code behind my Edit button in the my Home Index is:
{
"data": "Id",
"render": function (data, type, full, meta) {
return `<div class="text-center"> <a class="btn btn-info"
href="/Home/EditGet/` + data + `" >Edit</a> </div> `;
}
and my home controller methods are:
/// Get Edit
[HttpGet]
[Route("{Id}")]
public IActionResult EditGet(int? id)
{
if (id == null || id == 0)
{
return NotFound();
}
var obj = _sv.OpenRecord(id);
if (obj == null)
{
return NotFound();
}
return View("EditGet", obj);
}
/// Post Edit
[HttpPost]
public IActionResult EditPost(SalesVeiwModel sales)
{
if (ModelState.IsValid)
{
var res= _sv.Update(sales.Comment);
if (res==null )
{
return Json(data: "Not found");
}
return RedirectToAction("EditGet");
}
return Json(data: "Is not valid");
}
And finally my EditGet view is like bellow:
<form id="contact-form" method="post" asp-controller="Home" asp-
action="EditPost" role="form" >
<input asp-for="Id" hidden />
<div class="form-group">
<label>Invoice Nomber</label>
<input id="form_IBNo" type="text" class="form-control" disabled asp-for="IBNo">
</div>
.
.
.
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Confirm" asp-
controller="Home" asp-action="EditGet">
</form>
You should have two buttons,one call EditGet,one call EditPost,here is a demo:
<form id="contact-form" method="post" asp-controller="Home" asp-
action="EditPost" role="form" >
<input asp-for="Id" hidden />
<div class="form-group">
<label>Invoice Nomber</label>
<input id="form_IBNo" type="text" class="form-control" disabled asp-for="IBNo">
</div>
.
.
.
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Confirm">
<a class="btn btn-success btn-send" value="Confirm" asp-controller="Home" asp-action="EditGet" asp-route-id="1">EditGet</a>
</div>
</form>

Edit action in controller not updating

When I edit an item and return to the index view the item doesn't show what I updated it to.
I think I know what the problem is but not sure how to fix it. In my service class I have a CreateEditItem method and when I step thru the code it hits the if condition <=0. So it acts like there is an id of 0 when I click the submit button to submit my update. I'm not sure what to do to fix this. Do I need to have a separate method for Edit? And if so what should that look like?
public bool CreateEditItem(Item item)
{
if (item.ItemId <= 0)
{
var maxId = _mockList.Max(p => p.ItemId);
item.ItemId = maxId + 1;
_mockList.Add(item);
return true;
}
var itemToEdit = _mockList.FirstOrDefault(p => p.ItemId ==
item.ItemId);
itemToEdit = item;
return true;
}
Action in Controller
[HttpPost]
public IActionResult EditItem(Item itemToEdit)
{
_itemService.CreateEditItem(itemToEdit);
return RedirectToAction(nameof(Index), new { id =
itemToEdit.ItemId });
}
View:
<div class="row">
<form asp-action="EditItem">
<div asp-validation-summary="ModelOnly" class="text-
danger"></div>
<div class="container form-group">
<div class="row">
<div class="col-md-2">As Of : <label
for="AsOf" /></div>
<div class="col-md-4"><input id="AsOf"
value="#Model.ItemToEdit.AsOf" name="AsOf" type="date" /></div>
</div>
<br />
<div class="row">
<div class="col-md-2">Title Summary : <label
for="TitleSummary" /></div>
<div class="col-md-2"><input id="TitleSummary"
value="#Model.ItemToEdit.Title" name="Title" type="text" /></div>
</div>
<br />
<br />
<div class="row">
<div class="col-md-2"><input type="submit"
value="Submit" class="btn btn-primary" /></div>
</div>
</div>
</form>
</div>
I expect when I click the submit button to submit my update it will show the updated Title and/or AsOf date.
change your method from HTTPut to HttpPost
it will work.

ASP.NET MVC - Check Box List for Link Table Values

Hoping someone can help me out, what I am trying to achieve a checkbox list (populated from a database table) which then inserts into a link table.
I'm not sure how best to achieve this, this is what I have so far which displays correctly, but I'm not sure how I can get this to save.
#using (Html.BeginForm("Create", "ReviewChecklistsController"))
{
foreach (var item in ViewBag.ChecklistId)
{
<div class="checkbox">
<label>
<input type="checkbox"
name="#item.Value"
value="#item.Value" /> #item.Text
</label>
</div>
}
<p></p>
<div class="form-group">
<input type="submit" class="btn btn-success" value="Save Checklist" />
</div>
}
Below is how I have set it up in the database, if you need any more information please let me know. I am using Entity Framework.
What I want is ReviewChecklist\ChecklistId to map to List_Checklist\ChecklistId and then State is just a boolean so if the checkbox is checked or not.
I've managed to get it working using the below. Is this okay, or is there a better way to do it?
#using (Html.BeginForm("Create", "ReviewChecklistsController"))
{
int i = 0;
foreach (var item in ViewBag.ChecklistId)
{
var nameStatus = "reviewChecklist[" + i + "].Status";
var nameReviewId = "reviewChecklist[" + i + "].ReviewId";
var nameChecklistId = "reviewChecklist[" + i + "].ChecklistId";
#Html.HiddenFor(model => model.ReviewId, new { Name = nameReviewId })
#Html.HiddenFor(model => model.ChecklistId, new { Name = nameChecklistId, Value = item.Value })
<p>
#Html.CheckBoxFor(model => model.Status, new { Name = nameStatus })
#item.Text
</p>
i++;
}
<p></p>
<div class="form-group">
<input type="submit" class="btn btn-success" value="Save Checklist" />
</div>
}

Concatenation of strings in Razor MVC 5 for "class" attribute

I'm building an ASP.NET MVC 5 application for a local inventory. This app shows items on a page with buttons to deliver the items.
I want the "Scarica" buttons to be greyed-out when items are not available, so I thought I could just delete the btn-info attribute and that should've done the trick, so I changed the relevant lines of code in the view from this
<div class="col-sm-2">
#using (Html.BeginForm("ScaricaItem", "Scarico"))
{
string Disabilitato = "";
if (i.Qty == 0)
{
Disabilitato += "disabled";
}
<div class="pull-right">
#Html.HiddenFor(x => #i.Item.Modello)
#Html.Hidden("returnUrl", Request.Url.PathAndQuery)
<input type="submit" class="btn btn-info" value="Scarica" #Disabilitato />
</div>
}
</div>
to this:
<div class="col-sm-2">
#using (Html.BeginForm("ScaricaItem", "Scarico"))
{
string Disabilitato = "";
string Classe = "";
if (i.Qty == 0)
{
Disabilitato += "disabled";
Classe = "btn";
}
else
{
Classe = "btn btn-info";
}
<div class="pull-right">
#Html.HiddenFor(x => #i.Item.Modello)
#Html.Hidden("returnUrl", Request.Url.PathAndQuery)
<input type="submit" class=#Classe value="Scarica" #Disabilitato />
</div>
}
</div>
but now I have all the buttons greyed-out because the btn-info attribute value is treated as if it was an attribute itself
<input type="submit" class="btn" btn-info="" value="Scarica">
I also tried
<input type="submit" class=#(Classe) value="Scarica" #Disabilitato />
and
<input type="submit" class=#(String.Format("{0}", Classe)) value="Scarica" #Disabilitato />
but nothing changes.
Thanks,
Davide.

I need to call a controller by passing the param from the view on clicking the ActionLink

I am trying to search a student and display the student record based on the value entered on textbox. I am not sure how to pass the value without using Jquery. Is there a way.
Controller:
[Authorize]
public ActionResult GetStudentsByName(string name)
{
SchoolDbEntities db = new SchoolDbEntities();
var student = db.Students.Where(s => s.StudentName.Contains(name));
return View(student);
}
View
<div class="panel-body">
<div class="form-group">
#Html.LabelFor(m=> m.SearchEntity.StudentName,"Search Student")
#Html.TextBoxFor(m => m.SearchEntity.StudentName, new { #class = "form-control" })
</div>
</div>
<div class="panel-footer">
<button type="button" onclick="location.href='#Url.Action("GetStudentsByName", "Student")'" class="btn btn-primary">Search <i class="glyphicon glyphicon-search"></i></button>
<button id="Reset"
class="btn btn-primary btn-sm">
<i class="glyphicon glyphicon-share-alt"></i> Reset
</button>
</div>
I need to pass the param , In the #Url.Action("GetStudentsByName", "Student", new {#name= 'value from the textbox')
Also it is a Get Method and not httpPost.
You can keep the input form element inside a form control and submit the form via GET method.
Make sure the input element name matches with your action method parameter name
#using (Html.BeginForm("GetStudentsByName","Student",FormMethod.Get))
{
<input type="text" name="name"/>
<button type="submit" class="btn btn-primary">Search </button>
}
If you dont wanna make the button a submit button then by giving your text box a specific class you can do it .
<div class="panel-body">
<div class="form-group">
#Html.LabelFor(m=> m.SearchEntity.StudentName,"Search Student")
#Html.TextBoxFor(m => m.SearchEntity.StudentName, new { #class = "form-control,txt-input" })
</div>
</div>
<div class="panel-footer">
<button type="button" onclick="location.href='#Url.Action("GetStudentsByName", "Student",new { data= "STUDENT_NAME" })'.replace("STUDENT_NAME", $('.txt-input').val())" class="btn btn-primary">Search <i class="glyphicon glyphicon-search"></i></button>
<button id="Reset"
class="btn btn-primary btn-sm">
<i class="glyphicon glyphicon-share-alt"></i> Reset
</button>
</div>
I tried something like this long back , i think it should work.
Try this
View
#using (Html.BeginForm("GetStudentsByName", "Home"))
{
<div class="form-group">
#Html.LabelFor(m => m.StudentName, "Search Student")
#Html.TextBoxFor(m => m.StudentName, new { #class = "form-control" })
</div>
<input type="submit" value="Search" class="btn btn-primary" />
}
</div>
Controller
public ActionResult GetStudentsByName()
{
string name = Request.Form["StudentName"]
SchoolDbEntities db = new SchoolDbEntities();
var student = db.Students.Where(s => s.StudentName.Contains(name));
return View(student);
}
using Request.Form["StudentName"] you can access the value from view to controller. Also, one more suggestion, use using statement it helps to manage unhandled memory. For example
public ActionResult GetStudentsByName()
{
string name = Request.Form["StudentName"]
using(SchoolDbEntities db = new SchoolDbEntities())
{
var student = db.Students.Where(s => s.StudentName.Contains(name));
return View(student);
}
}

Resources