MVC loop in database table - c#

I have a form with some textboxfors.
one of the textbox is for a barcode.
Now when i give in that field a barcode and i click on make a order.
Then i want loop in the database for comparing the barcode with the correct article.
I have try with a foreach loop for loop and while loop but get Always a nullreferenceexception.
How can i loop in the database table for compare a textboxfor field with the database field ?
view
#model ReservatieMVC.ViewModels.AddtocartSubmit
#using EindwerkDatabase.lib.Models
<style>
#qtyTextbox {
width: 50px;
height: 35px;
bottom: 10px;
}
.submitCart {
float: right;
background-color: lightgray;
}
</style>
<div id="quantity">
#Html.Hidden("artikelId", ViewData["artikel"])
</div>
<div>#ViewBag.ArtikelId</div>
#{Html.BeginForm("Addtocart", "Artikels");}
<script>
$( document ).ready(function() {
.test = #Model.artikelId;
})
</script>
<div>
#Html.HiddenFor(m => m.artikelId, new { #class = "logger" })
<b>Barcode Student #Html.TextBoxFor(m => m.StudentBarCode)</b>
<b>Start UileenDatum: #Html.TextBoxFor(m => m.startdatum, new { id = "datepicker" }) #*<input type="text" id="datepicker" style="width:150px"*# </b>
<br /> <br />
<b>Teruggave: #Html.TextBoxFor(m => m.einddatum, new { id = "datepicker2" }) #*<input type="text" id="datepicker2" style="width:150px"*# </b>
</div>
<input class="submitCart" type="submit" value="Voeg toe">
#{Html.EndForm();}
controller
[HttpPost]
public ActionResult Addtocart(AddtocartSubmit model,Reservatie res)
{
Reservatie re = new Reservatie();
if (ModelState.IsValid)
{
while(model.StudentBarCode == res.Gebruiker.StudentBarCode)
{
break;
}
re.ArtikelId = model.artikelId;
//re.ArtikelId = model.artikelId;
string datumstart = model.startdatum;
string datumeind = model.einddatum;
re.startdatum = Convert.ToDateTime(datumstart);
re.einddatum = Convert.ToDateTime(datumeind);
re.GebruikerId = 3;
re.Datum = DateTime.Today;
r.Reservatie.Add(re);
r.SaveChanges();
return RedirectToAction("Index");
}
return PartialView();
}

Related

asp-action renders action="" instead of the correct URL

I have a method in my controller called "NewJobApp" that works fine and returns the view with "NewJobApp" model.
[AllowAnonymous]
[HttpGet("Consultant/NewJobApp/{agencyID:int}/{userID:int}/{companyID:int}/{jobID:int}")]
public async Task<ViewResult> NewJobApp(int agencyID, int userID, int companyID, int jobID)
{
NewJobApp nja = await Repository.GetNewJobApp(agencyID, userID, companyID, jobID);
return View(nja);
}
In the view I have a form that should call "SubmitNewJobApp", but when I view the page source, it shows action=""
<form id="JobAppForm" class="form-group" asp-controller="Consultant" asp-action="SubmitNewJobApp" method="post" style="text-align: left">
#Html.AntiForgeryToken()
<input id="AgencyID" asp-for="#Model.AgencyID" value="#Model.AgencyID" type="hidden" />
<input asp-for="#Model.AgencyName" value="#Model.AgencyName" type="hidden" />
<input asp-for="#Model.UserID" value="#Model.UserID" type="hidden" />
<input asp-for="#Model.CompanyID" value="#Model.CompanyID" type="hidden" />
<input asp-for="#Model.JobID" value="#Model.JobID" type="hidden" />
#if (!String.IsNullOrEmpty(Model.Errs))
{
#Html.Raw(Model.Errs);
}
<p style="margin: 0px; font-size: 8px"> </p>
<div class="form-group">
<label style="width: 120px; text-align: left; display: inline-block;" asp-for="#Model.JobTitle">Job:</label>
<input type="text" asp-for="#Model.JobTitle" value="#Model.JobTitle" readonly />
</div>
<div class="form-group">
<label style="width: 120px; text-align: left; display: inline-block;" asp-for="#Model.CompanyName">Company:</label>
<input type="text" asp-for="#Model.CompanyName" value="#Model.CompanyName" readonly />
</div>
<p style="margin-bottom: 4px;">Enter person search expression:</p>
<input asp-for="#Model.SearchExpression" value="#Model.SearchExpression" style="width: 132px; margin-bottom: 8px;" />
<button id="myButton" class="btn btn-primary" type="submit">Get Candidates</button>
<p style="margin: 0px; font-size: 8px"> </p>
<div class="form-group">
<label style="width: 120px; display: inline-block;" asp-for="ContactID">Contact:</label>
#Html.DropDownListFor(m => m.ContactID, Model.Contacts, "Choose a Contact", new { #class = "myDDL", #id = "contactsDDL" })
</div>
<div class="text-center" style="text-align: right">
<button id="btnSave" class="btn btn-primary" type="submit">Save</button>
</div>
</form>
This is the "SubmitNewJobApp" method in the controller, but it never gets called.
[HttpPost()]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SubmitNewJobApp(NewJobApp nj)
{
int id = 0;
bool is_err = false;
string err = string.Empty;
// check data
if (nj.ContactID == 0)
{
is_err = true;
}
// check model state
if (!ModelState.IsValid || is_err)
{
nj = await Repository.GetNewJobApp(nj);
return View("NewJobApp", nj);
}
nj.NewRecordID = id;
return View("NewJobApp", nj);
}
I still don't understand why this doesn't work, but I have a temporary solution.
If I remove the HttpGet template on the method that returns the "NewJobApp" view, the form action now contains a value, and works!
Previous method:
[AllowAnonymous]
[HttpGet("Consultant/NewJobApp/{agencyID:int}/{userID:int}/{companyID:int}/{jobID:int}")]
public async Task<ViewResult> NewJobApp(int agencyID, int userID, int companyID, int jobID)
{
NewJobApp nja = await Repository.GetNewJobApp(agencyID, userID, companyID, jobID);
return View(nja);
}
Now changed to:
[HttpGet()]
[AllowAnonymous]
public async Task<ViewResult> NewJobApp(int agencyID, int userID, int companyID, int jobID)
{
NewJobApp nja = await Repository.GetNewJobApp(agencyID, userID, companyID, jobID);
return View(nja);
}
This is the changed code that calls the "NewJobApp" controller method:
function startNewApplicant() {
var para1 = #ViewBag.AgencyID;
var para2 = #Model.Job.UserID;
var para3 = #Model.Job.CompanyID;
var para4 = #Model.Job.JobID;
// var url = "NewJobApp/" + para1 + "/" + para2 + "/" + para3 + "/" + para4; (previous)
var url = "NewJobApp?agencyID=" + para1 + "&userID=" + para2 + "&companyID=" + para3 + "&jobID=" + para4;
window.open(url, '_blank');
}
But actually I prefer to use the template because I want the cleaner looking URL.
My Startup routes:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "signin",
template: "{controller=Home}/{action=Index}/{agencyID}/{contactID}");
});

Comment boxes only post with first post in MVC

I have a view in my MVC application that is designed to show views and comments gathered from a database, and allow users to make posts and comments accordingly.
The relevant section of Html is below:
<div style="background-color:#fff1fc; height:100vh; width:810px; float:left; border-radius: 8px; margin: 5px">
<div>
<p>
<center>
#foreach (var item in Model.PostList)
{
<div style="background-color: white; height:auto; width: 810px; border-radius: 8px; margin: 5px; text-align: left; text-size-adjust: 50%; text-anchor:start; font-size: larger">
#Html.DisplayFor(modelItem => item.Profile.FirstName)
#Html.DisplayFor(modelItem => item.Profile.LastName)
#Html.DisplayFor(modelItem => item.Project.ProjectName)<br/>
<div style="text-align:center; text-size-adjust: auto">
#Html.DisplayFor(modelItem => item.Text)<br/>
</div>
<div style="text-align: right; text-size-adjust: 20%; text-anchor: end">
#Html.DisplayFor(modelItem => item.DATE)
</div>
<hr />
<div style="line-break:initial; font-size:small; text-align: left; margin: 10px; padding: 10px">
#Html.Label("Comments:")<br/>
<br/>
#foreach (var comment in Model.CommentList)
{
if (comment.PostId == item.Id)
{
#Html.DisplayFor(modelComment => comment.Profile.FirstName)
#Html.DisplayFor(modelComment => comment.Profile.LastName)
<br/>
<center>
#Html.DisplayFor(modelComment => comment.Comment1)
<hr />
<br/>
</center>
}
}
<center>
#Html.TextAreaFor(model => Model.Comment, new { #class = "height: 200px, width: 600px"})
<br />
<br />
<right>
<input type="submit" value="Comment" class="btn btn-default" />
<input type="hidden" name="PostId" value="#item.Id" />
<input type="hidden" name="ProfileId" value="#Model.ProfileList[0].Id" />
</right>
<br />
</center>
</div>
</div>
}
</center>
</p>
</div>
</div>
So, for each item in PostList, the relevant attributes of that list are displayed. With these posts, each item from the CommentList that references this post is also displayed, with a TextBox to make a new comment. This all works fine! The problem appears to be here:
<center>
#Html.TextAreaFor(model => Model.Comment, new { #class = "height: 200px, width: 600px"})
<br />
<br />
<right>
<input type="submit" value="Comment" class="btn btn-default" />
<input type="hidden" name="PostId" value="#item.Id" />
<input type="hidden" name="ProfileId" value="#Model.ProfileList[0].Id" />
</right>
<br />
</center>
For some reason, when I attempt to make a comment on my platform, it only works if commenting on the most recent/first post on the feed (The first item). Attempting to make a comment on anything other than the first item, does nothing. Here is the Post method of my controller:
public ActionResult Post(string Text, int Id, string Comment, int ProfileId, int PostId)
{
if (Text != "")
{
using (var ctx = new SocialDBEntities())
{
string userId = User.Identity.GetUserId();
Post post = new CrowdSocial2.Post();
post.ProfileId = Id;
post.DATE = System.DateTime.Now.Date;
post.Text = Text;
db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("Feed");
}
}
else if (Comment != "")
{
string userId = User.Identity.GetUserId();
Comment comment = new CrowdSocial2.Comment();
comment.PostId = PostId;
comment.ProfileId = ProfileId;
comment.Comment1 = Comment;
comment.Date = System.DateTime.Now.Date;
db.Comments.Add(comment);
db.SaveChanges();
return RedirectToAction("Feed");
}
else
{
return RedirectToAction("Feed");
}
}
The controller is passed Comment, and determines whether or not it is "null". If not, it will post the comment to the database with the accompanying postId and profileId. Since this wasn't working, I decided to put a breakpoint on the RedirectToAction both inside of the if(Comment != "") statement, and in the elseif statement to see what was happening.
Turns out, Comment for some reason is being passed as "" regardless of what was written in the comment box, the controller is seeing it as "" and hence just redirects back to the view. This makes me suspect that what is happening is that Comment is being passed from the very first comment box, which is empty.
Any ideas how I can fix this so that I can comment on any of the post items?

How to combine 2 tables using Entity Framework 6 and Linq in an MVC Project?

I want to know how to get data from relationals tables.
I want to get the images from the table named "Noticias1" that is relationated with "Noticias" (Noticias is an spanish word that means News sorry but it is for my University).
here the Diagram Image
Here my "Noticias1" table that gets the images that will contain the news in table "Noticias"
Here my "Noticia" Table that only contain 1 "Noticia" that means News in english
Here the actual view IMG
As you can see it only shows "Noticias" Table that only have 1 News that is not the problem.
Now I want to get the all the Images from "Noticias1" to every News in
the table "Noticias" to show it in my view. (the named 1_0 will be the
featured img).
Here my Controller
public class NoticiasController : Controller
{
// GET: Noticias
public ActionResult Index(int? page)
{
var entities = new Model.CobecaIntranetEntities();
//where n.FeHasta < DateTime.Now && n.Activo
var noticias = from n in entities.Noticias
where n.Activo && n.FeDesde <= DateTime.Now && DateTime.Now <= n.FeHasta
select n;
var noticiasArray = noticias.ToArray();
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(noticiasArray.ToPagedList(pageNumber, pageSize));
}
}
Here my View
#model PagedList.IPagedList<IntranetCorporativa.Model.Noticias>
#using PagedList;
#using PagedList.Mvc;
#{
var format = "dddd, MMMM dd, yyyy";
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_LayoutPage.cshtml";
string principalTitulo = Model[0].Titulo;
string principalContenido = Model[0].Contenido;
DateTime principalFechaDesde = Convert.ToDateTime(Model[0].FeDesde);
DateTime principalFechaHasta = Convert.ToDateTime(Model[0].FeHasta);
}
<script type="text/javascript">
function changeDisplay(e) {
var principalTitulo = $(e).text();
var principalContenido = $(e).siblings(".vNoticiaContenido:first").html();
var principalFecha = $(e).siblings(".vNoticiaFecha:first").val();
$("#currentprincipalTitulo").html(principalTitulo);
$("#currentprincipalContenido").html(principalContenido);
$("#currentprincipalFecha").html(principalFecha);
}
</script>
<style>
.uppercase {
text-transform: uppercase;
}
.limit {
text-overflow: ellipsis;
word-wrap: break-word;
overflow: hidden;
max-height: 3em;
line-height: 1.7em;
}
</style>
<!-- CONTENIDO -->
<div class="col-md-12 main">
<div class="header sec-title-hd">
<div class="bg-calendar"></div>
<div class="col-md-7">
<h5 class="pull-left">NOTICIAS</h5>
<div>
<img src="slider/img/arrow-left.png"> VOLVER
</div>
</div>
</div>
<div class="content-inter">
<div class="container-fluid sec-title-hd-sub">
<div class="row">
<div class="col-md-7">
<div>
<figure class="img_N">
<img id="currentprincipalImagen" src="#" class="img-responsive" alt="Here Principal IMG" />
<figcaption>
<p id="currentprincipalImagenTitulo">Here Img Description</p>
</figcaption>
</figure>
</div>
<div class="textnota">
<br>
<h5 id="currentprincipalTitulo" class="titulo_N uppercase">#principalTitulo</h5>
<p class="time">FeDesde: #principalFechaDesde.ToString(format)</p>
<p class="time">FeHasta: #principalFechaHasta.ToString(format)</p>
<p class="time">Hoy: #DateTime.Now.ToString(format)</p>
<div class="noti_P">
<p id="currentprincipalContenido">#principalContenido</p>
</div>
</div>
</div>
<div class="col-md-5">
<!-- Lado Derecho -->
#foreach (IntranetCorporativa.Model.Noticias n in Model)
{
<blockquote class="blockquote-nopadding bg-calendar-border-left">
<p class="time_f principalTitulo">#n.FeDesde.ToString(format)</p>
#n.Titulo
<p class="text-justify limit vNoticiaContenido">#n.Contenido</p>
</blockquote>
}
Págnia #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) de #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
<div>
</div>
</div>
</div>
</div>
</div>
</div>
Thanks for everyhing.
you will need a view model like this:
internal class NewsImagesViewModel
{
public string Title{ get; set; }
public IEnumerable<Image> Images { get; set; }
//... some other properties
}
In the Controller:
IList<NewsImagesViewModel> newsImagesList;
using (DbContext dbContext = new DbContext())
{
newsImagesList = dbContext.News
.Select(n => new NewsImagesViewModel
{
Title = n.Title,
Images = n.Images,
// ... some other properties you may need
}
.ToList();
}
return View(newsImagesList);
In the View
#model IEnumerable<Your.Namespace.NewsImagesViewModel>
#foreach(var item in Model)
{
//....
}
First, do yourself a favor and use better names for your classes and properties. You can modify them in the edmx designer as you like, an update won't destroy the changes. Change Noticias1 into the Spanish equivalent of NewsImage and rename the navigation properties.
Secondly, use Include to get the news images:
var noticias = from n in entities.Noticias.Include(n => n.Noticias2) // TODO: rename!!!
where n.Activo && n.FeDesde <= DateTime.Now && DateTime.Now <= n.FeHasta
select n;
Then somewhere within the #foreach (IntranetCorporativa.Model.Noticias n in Model) you're going to need a #foreach (var image in n.Noticias2) to display the images.

How to create a List<> hidden field and submit it to controller in MVC

I need to post back the items that the user added in the DevExpress ListBox, but, according to the company, the way to do it is to store the items in a hidden field and then submit it. I need to know how to create this hidden field, in the view, which, I believe, needs to be a List with Text and Value, (similar to the model passed) and then how to assign the values to it in jquery.
Notes:
1. The question is not how to create a hidden field, but that specific type.
2. The way it is now, in the controller, the model comes back as null.
// This code is located in the Index.cshtml page
<div id="modalMain" class="modal fade hidden-print" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" style="padding-bottom:0;padding-top:0">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div id="modalMainData" class="modal-body" style=" padding: 0 10px 0 10px !important;">
</div>
</div>
</div>
</div>
// This code is located on ListBoxItemsModal.cshtml
#model List<ValueText>
#using (Html.BeginForm("", "", FormMethod.Post, new { #id = "formPostListBoxItems" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class=" form-group">
#Html.Label("New Item text")
<div class="input-group">
#Html.TextBox("name", null, new { #id = "txtNewListBoxItem" })
<span class="input-group-btn">
<button id="btnAddListBoxItem" type="button" class="btn btn-default btn-xs">Add Item</button>
</span>
</div>
</div>
#Html.DevExpress().ListBox(settings =>
{
settings.Name = "ListBoxCarMake";
settings.Properties.EnableClientSideAPI = true;
settings.Properties.ValueField = "Value";
settings.Properties.ValueType = typeof(string);
settings.Properties.TextField = "Text";
}).BindList(Model).GetHtml()
}
// Add a new item to list box
$(document).on("click", "#btnAddListBoxItem", function () { s = $("#txtNewListBoxItem").val(); ListBoxCarMake.AddItem(s); });
$(document).on("click", "#btnPostListBoxItems", function (e) {
e.preventDefault();
err = '';
$.ajax({
url: '#Url.Action(("PostListBoxItems", "System")',
cache: false,
type: "POST",
data: $("#formPostListBoxItems").serialize(),
success: function (data) { $("#modalMainData").html(data); },
error: function (xhr, status, exception) { DisplayAjaxError(xhr, status, exception); }
});
});
// CONTROLLER
public ActionResult GetListOptions()
{
var model = new List<ValueText>();
model.Add(new ValueText() { Text = "AUDI", Value = "AUDI" });
model.Add(new ValueText() { Text = "BMW", Value = "BMW" });
model.Add(new ValueText() { Text = "VW", Value = "VW" });
return PartialView("~/Views/System/ListBoxItemsModal.cshtml", model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PostListBoxItems(List<ValueText> list)
{
return PartialView("~/Views/System/ListBoxItemsModal.cshtml", list);
}
#for (int i = 0; i < Model.Count; i++)
{
#Html.HiddenFor(modelitem => Model[i].Text)
#Html.HiddenFor(modelitem => Model[i].Value)
}
I suggest you to create a ListContainer and append its elements to your html as hidden inputs. This way, when the submit button is pressed, the values will go to the controller.

How do I get the value of my second dropdownlist in MVC4?

I've got these two cascading dropdown lists, they populate just fine. But when I hit submit I always gett NULL as the value of the second. My guess is that I have to do something with the javascript, but my skills in that department are seriously lacking. Please help!
Code removed, whole view added instead
I dont even have an HtmlHelper for the second dropdown, it just looks like this in the view:
Code removed, whole view added instead
Works just fine, I mean, it populates fine depending on what's chosen in the first dropdown. Maybe this is the part that needs alteration? The thing is I'm clueless.
EDIT:
This is the code that reads the information from the form and submits it to the database.
[HttpPost]
public ActionResult Returer(ReturerDB retur)
{
if (ModelState.IsValid)
{
db2.ReturerDB.AddObject(retur);
db2.SaveChanges();
return RedirectToAction("Returer");
}
return View("Returer");
}
EDIT2
The whole view code:
#model Fakturabolag.Models.ReturerDB
#{
ViewBag.Title = "Returer";
}
<script type="text/javascript" src="../../Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#bolag").prop("disabled", true);
$("#Kund").change(function () {
if ($("#Kund").val() != "- Välj bolag -") {
var options = {};
options.url = "/companies/getbolag";
options.type = "POST";
options.data = JSON.stringify({ country: $("#Kund").val() });
options.dataType = "json";
options.contentType = "application/json";
options.success = function (bolag) {
$("#bolag").empty();
for (var i = 0; i < bolag.length; i++) {
$("#bolag").append("<option>" + bolag[i] + "</option>");
}
$("#bolag").prop("disabled", false);
};
options.error = function () { alert("Fel vid bolagshämtning!"); };
$.ajax(options);
}
else {
$("#bolag").empty();
$("#bolag").prop("disabled", true);
}
});
});
</script>
<h2>Returer</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Returer</legend>
<br /><br />
<div class="editor-label">
<b>Kund</b>
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Kund, ViewData["kundLista"] as SelectList)
#Html.ValidationMessageFor(model => model.Kund)
</div>
<div class="editor-label">
<b>Bolag</b>
</div>
<select id="bolag"></select>
<div class="editor-label">
<b>Pris</b>
</div>
<div class="editor-field">
#Html.TextBox("pris", null, new { style = "width: 150px" })
#Html.ValidationMessageFor(model => model.Pris)
</div>
<div class="editor-label">
<b>Datum</b>
</div>
<div class="editor-field">
#Html.TextBox("datum", ViewData["datum"] as String, new { style = "width: 150px" })
#Html.ValidationMessageFor(model => model.Datum)
</div>
<p>
<input type="submit" value="Lägg till" />
</p>
</fieldset>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Currently you are not retrieving the additional value "bolag" in your action. I guess your model does not have property named "bolag". You can either add that or you can add additional parameter to you action like so:
[HttpPost]
public ActionResult Returer(ReturerDB retur, string bolag)
{
if (ModelState.IsValid)
{
db2.ReturerDB.AddObject(retur);
db2.SaveChanges();
return RedirectToAction("Returer");
}
return View("Returer");
}
After that, the selected value from the dropdown should automatically be in the bolag-parameter.
Edit.
You also need to add name-attribute to your select:
<select id="bolag" name="bolag"/>

Categories