I am connected with the ado.net entity model. I can retrieve information from the database using the Dropdownlist, but I am not able to commit changes (Insert) into the database. It previously works fine two days ago, but just stop working today. I have tried every trick in similar topics but no changes.
My Controlller:
public class RimySaleController : Controller
{
// GET: RimySale
// dropdownlist
public ActionResult RimSaleIndex()
{
newLayanDBEntities17 db = new newLayanDBEntities17();
List<Rim> list = db.Rims.ToList();
ViewBag.RimName = new SelectList(list, "rim_id", "rim_name");
List<Employee> lists = db.Employees.ToList();
ViewBag.EmpName = new SelectList(lists, "emp_id", "emp_name");
List<Customer> listp = db.Customers.ToList();
ViewBag.CustName = new SelectList(listp, "cust_id", "cust_name");
return View();
}
public ActionResult RimSaleSave(RimSale model)
{
try
{
newLayanDBEntities17 db = new newLayanDBEntities17();
Rim_Sale addRim = new Rim_Sale();
addRim.Date = model.Date;
addRim.cust_int = model.Cust_int;
addRim.emp_id = model.Emp_id;
addRim.rim_id = model.Rim_id;
addRim.rim_sold_quantity = model.Rim_sold_quantity;
addRim.rim_sold_unit_price = model.Rim_sold_unit_price;
//making the changes
db.Rim_Sale.Add(addRim);
db.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
return RedirectToAction("RimSaleIndex");
}
}
}
My View:
#using (Html.BeginForm("SaveBattSale", "BatterySale", FormMethod.Post))
{
<br />
#Html.TextBoxFor(model => model.Sold_date, new { #type = "Date", #class = "form-control" })
<br />
#Html.DropDownListFor(model => model.Bat_id, ViewBag.BattName as SelectList, "--Select Battery--", new { #class = "form-control" })
<br />
#Html.TextBoxFor(model => model.Batt_sold_quantity, new { #type = "number", #placeholder = "Type Quantity Sold", #class = "form-control " })
<br />
#Html.TextBoxFor(model => model.Batt_unit_price, new { #placeholder = "Price Paid for One Battery", #type = "number", #class = "form-control" })
<br />
#Html.DropDownListFor(model => model.Cust_id, ViewBag.CustName as SelectList, "--Select Customer--", new { #class = "form-control" })
<br />
#Html.DropDownListFor(model => model.Emp_id, ViewBag.EmpName as SelectList, "--Select Employee--", new { #class = "form-control" })
<br />
<input type="Submit" value=" Submit" /> <input type="reset" value=" Reset" />
<br />
}
Your code looks ok. Try another one approach to insert data:
using (var db = new YourEntities())
{
Rim_Sale addRim = new Rim_Sale();
addRim.Date = model.Date;
addRim.cust_int = model.Cust_int;
addRim.emp_id = model.Emp_id;
addRim.rim_id = model.Rim_id;
addRim.rim_sold_quantity = model.Rim_sold_quantity;
addRim.rim_sold_unit_price = model.Rim_sold_unit_price;
db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Rim_Sale] ON");
//making the changes
db.Rim_Sale.Add(addRim);
db.SaveChanges()
db.Entry(addRim).State = EntityState.Added;
db.SaveChanges();
db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Rim_Sale] OFF");
}
If data is not inserted, then there is a chance that you are inserting data to another database. If you use localDb, then make sure that a property of .mdf file in your solution as Copy to output Directory: "Copy only if newer", otherwise your db file will overwrite every time it runs.
UPDATE:
It is not a good way, but give a try:
db.Database.ExecuteSqlCommand(
"Insert into Rim_Sale Values(#Date, #cust_int, #emp_id, #rim_id,
#rim_sold_quantity , #rim_sold_unit_price )",
new SqlParameter("Date", Date),
new SqlParameter("cust_int", cust_int),
new SqlParameter("emp_id", emp_id),
new SqlParameter("rim_id", rim_id),
new SqlParameter("rim_sold_quantity ", rim_sold_quantity ),
new SqlParameter("rim_sold_unit_price ", rim_sold_unit_price ),
);
Related
This question already has answers here:
The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'
(6 answers)
Closed 5 years ago.
Hi everyone I am trying to add a dropdownlist to my create view that will contain a list of all users in the distributee role I was sure I had set this up correctly but any time I attempt to open the create page I receive
{"There is no ViewData item of type 'IEnumerable' that has the key 'UserId'."}
controller method
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Document Author")]
public ActionResult Create([Bind(Include = "DocumentID,DocTitle,RevisionNumber,DocumentAuthor,CreationDate,ActivationDate,DocumentStatus,FilePath,Distributee") ] Document document, HttpPostedFileBase file, object selectedName = null)
{
try
{
if (file.ContentLength > 0)
{
string _FileName = Path.GetFileName(file.FileName);
string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);
file.SaveAs(_path);
document.CreationDate = DateTime.Now;
document.ActivationDate = DateTime.Now;
document.DocumentAuthor = User.Identity.Name;
document.DocumentStatus = "Draft";
document.FilePath = _path;
}
if (ModelState.IsValid)
{
ViewBag.Message = "File Uploaded Successfully!!";
db.Documents.Add(document);
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch
{
ViewBag.Message = "File upload failed!!";
return View(document);
}
var nameQuery = from user in db.Users
where user.Roles.Any(r => r.RoleId == "4ba13c9f-2403-45ad-961e-7c5cb6b08bc9")
orderby user.FirstName
select new
{
Id = user.Id,
Name = user.FirstName + " " + user.LastName
};
ViewBag.UserId = new SelectList(nameQuery, "Id", "Name", selectedName);
return View(document);
}
view
#model IP3Latest.Models.Document
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm("Create", "Documents", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Document</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.DocTitle, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DocTitle, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DocTitle, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RevisionNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RevisionNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RevisionNumber, "", new { #class = "text-danger" })
</div>
</div>
<div>
#Html.DropDownList("UserId")
</div>
<div>
#Html.TextBox("file", "", new { type = "file" }) <br />
<input type="submit" value="Upload" />
#ViewBag.Message
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I checked all of the other questions about this and they all seemed to be a bit different so any help you could offer would be appreciated.
Your issue is right here:
catch
{
ViewBag.Message = "File upload failed!!";
return View(document);
}
When you run into an an error and the execution goes into the catch block, you are not setting the UserId property. Later your view looks for that property in this line:
#Html.DropDownList("UserId")
And since it cannot find it, it starts complaining. To fix it, you need to set the UserId property in the catch block as well. Having said that, a better question you may want to ask yourself is why you are ending up in the catch block? And since the block is a catch all block, you may have issues in your code anywhere in your try block.
The other issue is that once you have fixed the above, you will still have an issue because the UserId will be the name of the parameter submitted to the action method, not selectedName as you have in your action method.
I'm trying to get the create function to have the user selected values entered into the database. When the create button is pushed, no error is thrown but, the data is not populated. I'm pretty sure my frequency fields are causing the issue but have been unable to come with a solution.
There are two different types of frequencies a user can select depending upon their "Notification Name" selection. One selection has 3 separate fields for a numerical value, time frame (week, month etc.), and a before/after selection. The other simply states instantaneous as a static text field. Regardless of which option is chosen the frequency data should be populated into one cell within the database which is then separated using piping where necessary. I'm still pretty new to C# MVC so any help is greatly appreciated.
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,notificationType1,recipientTypeId,frequency")] NotificationType notificationType)
{
if (ModelState.IsValid)
{
db.NotificationType.Add(notificationType);
db.SaveChanges();
return RedirectToAction("Create");
}
ViewBag.recipientTypeId = new SelectList(db.RecipientType, "Id", "recipientRole", notificationType.recipientTypeId);
return View(notificationType);
}
View
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.notificationType1, "Notification Name", htmlAttributes: new { #class = "control-label col-md-2 helper-format" })
<div class="col-md-10" id="type_selection">
#Html.DropDownList("notificationType1", new List<SelectListItem> {
new SelectListItem { Text = "Make a Selection", Value="" },
new SelectListItem { Text = "Incomplete Documents", Value= "Incomplete Documents" },
new SelectListItem { Text = "All Documents Complete", Value = "All Documents Complete" },
new SelectListItem { Text = "Documents Requiring Action", Value = "Documents Requiring Action" }
}, new { #class = "helper-format", #id = "value_select", style = "font-family: 'Roboto', Sans Serif;" })
#Html.ValidationMessageFor(model => model.notificationType1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" id="frequency_group">
#Html.LabelFor(model => model.frequency, "Frequency", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-sm-3" id="frequency_group">
#Html.TextBoxFor(model => model.frequency, new { #class = "textbox-width", #placeholder = "42" })
#Html.DropDownList("frequency", new List<SelectListItem>
{
new SelectListItem { Text = "Day(s)", Value= "| Day"},
new SelectListItem { Text = "Week(s)", Value= "| Week"},
new SelectListItem { Text = "Month(s)", Value= "| Month"}
})
#Html.DropDownList("frequency", new List<SelectListItem>
{
new SelectListItem { Text = "Before", Value= "| Before"},
new SelectListItem { Text = "After", Value= "| After"}
})
</div>
<p class="col-sm-2" id="psdatetext">The Beginning</p>
</div>
<div class="form-group" id="freq_instant">
#Html.LabelFor(model => model.frequency, "Frequency", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="instant_text">
<p>Instantaneous</p></div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.recipientTypeId, "Notification For", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("recipientTypeId", new List<SelectListItem>
{
new SelectListItem { Text = "Me", Value= "Me"},
new SelectListItem { Text = "Account Manager", Value="Account Manager" },
new SelectListItem { Text = "Candidate", Value= "Candidate"},
new SelectListItem { Text = "Recruiter", Value="Recruiter" },
new SelectListItem { Text = "Manager", Value= "Manager"}
})
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1 col-md-10">
<div id="hovercreate">
<button type="submit" value="CREATE" class="btn btn-primary" id="createbtn">CREATE</button>
</div>
</div>
</div>
</div>
}
JS for frequency options
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(document).ready(function () {
$('#frequency_group').hide()
$('#freq_instant').hide()
$('#value_select').change(function () {
var selection = $('#value_select').val();
$('#frequency_group').hide();
switch (selection) {
case 'Incomplete Documents':
$('#frequency_group').show();
break;
case 'All Documents Complete':
$('#frequency_group').show();
break;
}
});
$('#value_select').on('change', function () {
if (this.value == 'Documents Requiring Action') {
$("#freq_instant").show();
}
else {
$("#freq_instant").hide();
}
});
});
Have you placed a break-point on the method? And if so, is it triggering?
If not, try this...
From what I remember, all Controllers has a default parameter of ID which is set in the RouteConfig.cs file (App_Start/RouteConfig.cs).
There's a couple of ways to go from there.
1. Give the controller the ID parameter (e.g. (int ID))
2. Set the route value via the Route attribute
To do this you need to -
A. Add the following at the top of your RouteConfig.cs / RegisterRoutes method.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//...
}
B. Add
[ValidateAntiForgeryToken]
[Route(#"Create/")]
public ActionResult Create([Bind(Include = ...
{
I would also suggest putting a break-point at the beginning of the method to see if its hitting it.
http://www.tutorialsteacher.com/mvc/routing-in-mvc
https://msdn.microsoft.com/en-us/library/system.web.mvc.routecollectionattributeroutingextensions.mapmvcattributeroutes%28v=vs.118%29.aspx
Is the Id key manually assigned? If not (for example, if it's an IDENTITY field), you shouldn't be binding it - remove Id from [Bind(Include = "...")].
I am trying to show multiple columns from my database in a dropdownlist using a SelectList
public ActionResult Create()
{
var times = db.Show_Courses
.Select(x =>
new {
id = x.show_course_id,
times = x.show_course_before + "," + x.show_course_after
});
ViewBag.course_id = new SelectList(times, "id", "times");
return View();
}
It shows up properly in the view but in the database the value of the id is 0
This was my code before i wanted to show two columns in the textfield of the selectlist
public ActionResult Create()
{
ViewBag.course_id = new SelectList(db.Show_Courses, "show_course_id", "show_course_time_before");
return View();
}
And here is my code in the view
<div class="form-group">
#Html.LabelFor(model => model.course_show_id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("course show id", (SelectList)ViewBag.course_id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.course_show_id, "", new { #class = "text-danger" })
</div>
</div>
So my question is how can I display 2 values in the Textfield of the Selectlist without the id becoming 0?
You could generate SelectList manually.
For example,
ViewBag.course_id = db.Show_Courses
.Select(x => new SelectListItem {
Text = x.show_course_before + "," + x.show_course_after,
Value = x.show_course_id.ToString() })
.ToList();
I personally like to use strongly type model. You can read more here
Your code seems to be fine, you need to map the dropdown to according value from model: show_course_id - from what I see, so please update your dropdown to:
#Html.DropDownList("show_course_id", (SelectList)ViewBag.course_id, new { htmlAttributes = new { #class = "form-control" } })
I want to upload an image into a database (ShoppingItems) OR save the image to a folder in my project and insert the path of the image into the db. Can anybody help? This is my code (view):
#using (Html.BeginForm("Index3", "Upload", FormMethod.Post))
{
#Html.TextBoxFor(x => x.Itemname, new { #class = "form-control", placeholder = "Item name", required = "required" })
<br />
#Html.TextBoxFor(x => x.Price, new { #class = "form-control", placeholder = "Item price", required = "required" })
<br />
#Html.TextBoxFor(x => x.Quantity, new { #class = "form-control", placeholder = "Item quantity"})
<br />
#Html.TextBoxFor(x => x.AuthorIdentity, new { #class = "form-control", placeholder = "Username", required = "required" })
<br />
// THIS IS WHERE MY IMAGE UPLOAD SHOULD BE
<br />
#Html.TextBoxFor(x => x.Category, new { #class = "form-control", placeholder = "Item category", required = "required" })
<br />
#Html.TextAreaFor(x => x.Description, new { #class = "form-control", placeholder = "Item description", required = "required" })
<br />
<input type="submit" class="btn btn-danger" value="Add" />
}
Controller:
public ActionResult Index3(ShoppingItem formModel);
{
using (var ctx = new GikGamerModelDataContext())
{
if (formModel == null)
return View();
ctx.ShoppingItems.InsertOnSubmit(formModel);
ctx.SubmitChanges();
}
return View();
}
My upload index (Index3) just shows text that says that your upload was successful or unsuccessful so I haven't added it :)
in the form in order to upload you have to specify the attribute enctype : with the value "multipart/form-data"
You can foloow the examples in this response to try it : Uploading/Displaying Images in MVC 4
Hope it helps
My problem is:
I have two fields, and when i call my #Html.Actionlink method it send a null value for these two parameters.
This is my page code:
<div id="new-skill" class="row">
<label for="Description">Descreva brevemente a sua habilidade:</label>
#Html.TextBoxFor(model => model.skill.Description, new { #class = "form-control" })
<label for="Name">Em qual categoria ela está?</label>
#Html.TextBoxFor(model => model.skill.Category.Name, new { #class = "form-control" })
<div class="text-center margin-top15">
#Html.ActionLink("Adicionar nova habilidade", "InsertNewSkill", new
{
professionalId = ViewBag.professionalId,
skillDescription = "Test Text",
categoryName = Model.skill.Category.Name
}, new
{
#class = ""
})
</div>
</div>
This is my InsertNewSkill method:
public ActionResult InsertNewSkill(int professionalId, string skillDescription, string categoryName)
{
initBusinessObjects();
var professional = professionalBusiness.GetById(professionalId);
var newSkill = new SkillModel { Description = skillDescription, Category = new SkillCategoryModel { Name = categoryName } };
skillBusiness.Insert(newSkill);
professional.Skills.Add(newSkill);
professionalBusiness.Update(professional);
return View();
}
What I must to do to achieve this (send the textbox values)?
Have you tried adding the controllerName to your actionLink?
#Html.ActionLink("Adicionar nova habilidade", "InsertNewSkill","CONTROLLER_NAME", new
{
professionalId = ViewBag.professionalId,
skillDescription = "Test Text",
categoryName = Model.skill.Category.Name
}, new
{
#class = ""
})
Without using jQuery / javascript, you should use a form to get those values back to the server.
#{using(Html.BeginForm("InsertNewSkill", "ControllerName", FormMethod.Get)){
<div id="new-skill" class="row">
<label for="Description">Descreva brevemente a sua habilidade:</label>
#Html.TextBoxFor(model => model.skill.Description, new { #class = "form-control" })
<label for="Name">Em qual categoria ela está?</label>
#Html.TextBoxFor(model => model.skill.Category.Name, new { #class = "form-control" })
#Html.Hidden("professionalId", ViewBag.professionalId)
<div class="text-center margin-top15">
<input type="submit" value="Adicionar nova habilidade"/>
}}
With that said, typically you should POST these values back to the server and then redirect to a new ActionMethod (Thus, the acronym PRG for Post, Redirect, Get).