C# Razor trying to populate textbox from Dropdown - c#

I am trying to build a EF C# Razor application. I continue to fail in endeavor to have the dropdown box[listbox]'s choice call a route called getRecruiter(with that value) and change the recruitername textbox to the recruiter.
It errors saying: Uncaught ReferenceError: RecruiterName is not defined
If anyone could help me, I would greatly appreciate it. I am trying to learn how to use Razor and C# and have tried everything I could find online.
Here is the relevant code:
Notes Model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace JOM.Models
{
public class NotesModel
{
[Key]
public int NotesID { get; set; }
public int JobID { get; set; }
public string Recruiter { get; set; }
public string NoteTitle { get; set; }
public string NoteData { get; set; }
public DateTime ActiveDate { get; set; }
}
public class JobWithRecruiter
{
public int JobID { get; set; }
public string RecruiterName { get; set; }
}
}
Notes Controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using JOM.DAL;
using JOM.Models;
namespace JOM.Controllers
{
public class NotesModelsController : Controller
{
private JobsContext db = new JobsContext();
// GET: NotesModels
public ActionResult Index()
{
IEnumerable<JobModel> jobs = db.Jobs;
ViewData["jobs"] = jobs;
return View(db.Notes.ToList());
}
// GET: NotesModels/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
NotesModel notesModel = db.Notes.Find(id);
if (notesModel == null)
{
return HttpNotFound();
}
return View(notesModel);
}
// GET: NotesModels/Create
public ActionResult Create()
{
IEnumerable<JobModel> jobs = db.Jobs;
ViewData["jobs"] = jobs;
return View();
}
// POST: NotesModels/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "NotesID,JobID,Recruiter,NoteTitle,NoteData,ActiveDate")] NotesModel notesModel)
{
ViewBag.Jobs =
from job in db.Jobs
select job;
ViewBag.Recruiters =
from job in db.Jobs
join note in db.Notes on job.JobID equals note.JobID
select new JobWithRecruiter { JobID = job.JobID, RecruiterName = note.Recruiter };
if (ModelState.IsValid)
{
db.Notes.Add(notesModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(notesModel);
}
// GET: NotesModels/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
NotesModel notesModel = db.Notes.Find(id);
if (notesModel == null)
{
return HttpNotFound();
}
return View(notesModel);
}
// POST: NotesModels/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "NotesID,JobID,Recruiter,NoteTitle,NoteData,ActiveDate")] NotesModel notesModel)
{
if (ModelState.IsValid)
{
db.Entry(notesModel).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(notesModel);
}
// GET: NotesModels/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
NotesModel notesModel = db.Notes.Find(id);
if (notesModel == null)
{
return HttpNotFound();
}
return View(notesModel);
}
// POST: NotesModels/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
NotesModel notesModel = db.Notes.Find(id);
db.Notes.Remove(notesModel);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Notes View:
#model JOM.Models.NotesModel
#using JOM.Models;
#{
ViewBag.Title = "Create";
}
#functions
{
public string getRecruiter(int jobID)
{
if (jobID > 0)
{
var j = (IEnumerable<JobWithRecruiter>)ViewBag.Recruiters;
return j.Where(jo => jo.JobID.Equals(jobID)).First<JobWithRecruiter>().RecruiterName;
}
return "No Name Selected";
}
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Notes</h4>
<hr />
#{
int selectedJobID = 0;
string RecruiterName = "Not Selected";
}
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label class="control-label col-md-2" for="JobDesc">Choose Job:</label>
<div class="col-md-10">
#{
var jobs = (IEnumerable<JobModel>)ViewBag.Jobs;
}
#Html.DropDownList("listbox", jobs.Select(item => new SelectListItem
{
Value = item.JobID.ToString(),
Text = item.JobDesc.ToString()
}))
<script language="Javascript">
$(document).ready(function () {
$('#listbox').change(function () {
selectedJobID = $(this).val();
#{
RecruiterName = getRecruiter(selectedJobID);
}
$('#recruiter').val(RecruiterName);
});
});
</script>
</div>
</div>
<div class="form-group">
#Html.Label("Recruiter", htmlAttributes: new {#class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBox(RecruiterName, RecruiterName,new { ID="recruiter", #class = "form-control" });
#Html.ValidationMessageFor(model => model.Recruiter, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NoteTitle, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NoteTitle, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NoteTitle, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NoteData, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NoteData, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NoteData, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ActiveDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ActiveDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ActiveDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}

You can't invoke C# code like if it was JS code, so this
$(document).ready(function () {
$('#listbox').change(function () {
selectedJobID = $(this).val();
#{
RecruiterName = getRecruiter(selectedJobID);
}
$('#recruiter').val(RecruiterName);
});
});
doesn't mean RecruiterName = getRecruiter(selectedJobID); will be assigned when you change value of #listbox dropdown.
What you could do is preparing JSON collection containing all your recruiters inside controller and pass it to your view. Then you could use only JS (which would work used like you tried with C# code) to retrieve recruiters name based on ID.

In controller invoke list:
[HttpPost]
public ActionResult bindCityList(int stateid)
{
List<SelectListItem> lstcity = new List<SelectListItem>();
try
{
Panel cs = new Panel();
DataTable dt = new DataTable();
dt = cs.getCityVsState(Conn, stateid);
foreach (System.Data.DataRow dr in dt.Rows)
{
lstcity.Add(new SelectListItem { Text = #dr["CityName"].ToString(), Value = #dr["CityID"].ToString() });
}
}
catch (Exception ex)
{
logger.WriteErrorToFile("Panel::bind City List :" + ex.Message.ToString());
}
finally
{
Conn.Close();
}
return Json(lstcity.AsEnumerable());
}
In view --
On change of state dropdown bind city list
$('#ddlstate').change(function () {
var url = "bindCityList";
$.ajax({
url: url,
data: { stateid: $('#ddlstate').val() },
cache: false,
type: "POST",
success: function (data) {
$("#ddlcity").empty();
var markup = "<option value='0'>---Select---</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value='" + data[x].Value + "'>" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});

Related

I want to update one attribute of an element in carts without updating database. What should I write in edit method?

Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication2.Models;
namespace WebApplication2.Controllers
{
public class CartController : Controller
{
public ActionResult Index()
{
return RedirectToAction("Index", "Products");
}
// GET: Cart
private NorthwindDataContext dbContext = new NorthwindDataContext();
private List<Cart> carts;
public List<Cart> GetListCarts()
{
carts = Session["Cart"] as List<Cart>;
if (carts == null)
{
carts = new List<Cart>();
Session["Cart"] = carts;
}
return carts;
}
public ActionResult AddCart(int id)
{
carts = GetListCarts();
Cart c = carts.Find(s => s.ProductID == id);
if (c == null)
{
c = new Cart(id);
carts.Add(c);
}
else
c.Quantity++;
return RedirectToAction("ListCarts");
}
public ActionResult ListCarts()
{
carts = GetListCarts();
ViewBag.CountProduct = carts.Sum(s=>s.Quantity);
ViewBag.Total = carts.Sum(s => s.Total);
return View(carts);
}
public ActionResult Edit(int id)
{
carts = GetListCarts();
var p = carts.Find(s => s.ProductID == id);
return View(p);
}
[HttpPatch]
public ActionResult Edit(int id, FormCollection collection)
{
carts = GetListCarts();
int c = carts.FindIndex(s => s.ProductID == id);
if (c != -1)
carts[c].Quantity = int.Parse(collection["Quantity"]);
UpdateModel(carts);
return RedirectToAction("ListCarts");
}
public ActionResult Delete(int id)
{
carts = GetListCarts();
Cart c = carts.Find(s => s.ProductID == id);
if (c != null)
carts.RemoveAll(s=>s.ProductID== id);
return RedirectToAction("ListCarts");
}
}
}
Model:
public class Cart
{
private NorthwindDataContext dbContext = new NorthwindDataContext();
public int ProductID { get; set; }
public string ProductName { get; set; }
public decimal? UnitPrice { get; set; }
public int Quantity { get; set; }
public decimal? Total { get => UnitPrice * Quantity; }
public Cart(int pID)
{
this.ProductID = pID;
Product p = dbContext.Products.Single(n=>n.ProductID==pID);
ProductName = p.ProductName;
UnitPrice = p.UnitPrice;
Quantity = 1;
}
}
View:
#model WebApplication2.Models.Cart
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Cart</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ProductID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.ProductID, new { #readonly = "readonly" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.ProductName, new { #readonly = "readonly" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UnitPrice, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.UnitPrice, new { #readonly = "readonly" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Quantity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Quantity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Tried:
When I clicked Edit then Save button, nothing happened.
[HttpPatch]
public ActionResult Edit(int id, FormCollection collection)
{
carts = GetListCarts();
int c = carts.FindIndex(s => s.ProductID == id);
if (c != -1)
carts[c].Quantity = int.Parse(collection["Quantity"]);
UpdateModel(carts);
return RedirectToAction("ListCarts");
}
Expected:
When I click Edit, the page moves to Edit View and I can change Quantity field then I click Save button. After that, the page redirects to ListCarts and the field I changed should be updated. But there is something wrong in the above code, please fix me. Fmi, I changed some fields to readonly textbox in Edit View. Does that affect the method?

populating dropdown menu from database in ASP.NET MVC [duplicate]

This question already has answers here:
Populating a razor dropdownlist from a List<object> in MVC
(9 answers)
Closed 3 years ago.
I have a view to create an 'Appointment' after choosing some options in 3 different drop-down menus (Patient, Doctor, Clinic)
I need help with creating and populating these 3 drop-down menus.
I'm pretty new to ASP.NET MVC and C#. So, your help is most appreciated.
I'll include the appointment controller and appointment creation view code.
AppointmentController
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ClinicManagement.Models;
namespace ClinicManagement.Controllers
{
public class AppointmentController : Controller
{
// GET: Appointment
public ActionResult Index()
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
return View(DataBase.Appointments.ToList());
}
}
// GET: Appointment/Details/5
public ActionResult Details(int id)
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
return View(DataBase.Appointments.Where(x => x.AppintID == id).FirstOrDefault());
}
}
// GET: Appointment/Create
public ActionResult Create()
{
return View();
}
// POST: Appointment/Create
[HttpPost]
public ActionResult Create(Appointment appointment)
{
try
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
DataBase.Appointments.Add(appointment);
DataBase.SaveChanges();
}
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Appointment/Edit/5
public ActionResult Edit(int id)
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
return View(DataBase.Appointments.Where(x => x.AppintID == id).FirstOrDefault());
}
}
// POST: Appointment/Edit/5
[HttpPost]
public ActionResult Edit(int id, Appointment appointment)
{
try
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
DataBase.Entry(appointment).State = EntityState.Modified;
DataBase.SaveChanges();
}
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Appointment/Delete/5
public ActionResult Delete(int id)
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
return View(DataBase.Appointments.Where(x => x.AppintID == id).FirstOrDefault());
}
}
// POST: Appointment/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
Appointment appointment = (DataBase.Appointments.Where(x => x.AppintID == id).FirstOrDefault());
DataBase.Appointments.Remove(appointment);
DataBase.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Appointment 'Create' View
#model ClinicManagement.Models.Appointment
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Appointment</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.DoctorID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DoctorID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DoctorID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PatientID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PatientID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PatientID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ClinicID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ClinicID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ClinicID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create Appointment" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
If the drop down menu options are in a database, why not add a list to your model, populate that list in your GET ActionMethod and then render it using the DropdownListFor helper tag.
For example...
public class Appointment
{
public IEnumerable<SelectListItem> Clinic {get; set;}
//You should add this for every dropdown menu you intend to put in the list.
//I am guessing you already have a model like this as this was not in the question
}
public class Clinic
{
public int ClinicId {get; set;}
public string ClinicName {get; set;}
}
In the controller, you can then query the database for the options
public ActionResult Create()
{
var Clinic = context.Clinic.ToList();
var model = new Appointments()
{
Clinic = Clinic.Select(x => new SelectListItem
{
Value = x.ClinicId.ToString(),
Text = x.ClinicName
}
}
return View(model);
}
Like before, you would have to do this for all the fields. If you are worried about the numerous roundtrip to the database to get the values, do some research about Z.EntityFrameWork nuget pakages that lets you run batch SQL statements so you can get all three results with one database round trip.
Then in the view, you can do this...
#Html.DropDownListFor(m => m.ClinicId, Model.Clinic, "Select Clinic", new { #class = "form-control", id = "clinic" })
In Create controller GET , you should create 3 viewbag like
ViewBag.Patient = Database.Patient.ToList();
...
and in view, use dropdownlist:
#Html.DropDownList("PatientId", new SelectList(ViewBag.Accounts, "PatientId", "PatientName")), "choose the patient", new { #class = "form-control" }))

One of two model for View is always null in MVC 5

In my MVC5 application I have two model Order and File as following:
public class Order
{
public int OrderID { get; set; }
public string OrderName{ get; set; }
}
public class File
{
public HttpPostedFileBase[] files { get; set; }
}
I want edit objects of both classes in single view, so I create parent class:
public class MainContext
{
public Order Order { get; set; }
public File File { get; set; }
}
In the view I have this:
#using (Html.BeginForm("Create", "Order", FormMethod.Post, new { encType = "multipart/form-data" }))
#Html.AntiForgeryToken()
<div class="form-group">
<label>OrderName</label>
#Html.EditorFor(model => model.Order.OrderName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Order.OrderName, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.File.files, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.File.files, "", new { #type = "file", #multiple = "multiple", })
#Html.ValidationMessageFor(model => model.File.files, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<input type="submit" value="submit" class="btn btn-success btn-lg btn-block" />
</div>
The Controller
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "OrderName")] Order order, HttpPostedFileBase[] files)
{
if (ModelState.IsValid)
{
db.Order.Add(order);
db.SaveChanges();
if (files != null)
{
foreach (HttpPostedFileBase file in files)
{
if (file != null)
{
var InputFileName = Path.GetFileName(file.FileName);
var ServerSavePath = Path.Combine(Server.MapPath("~/UploadedFiles/") + InputFileName);
file.SaveAs(ServerSavePath);
}
}
}
return RedirectToAction("Index");
}
}
Now the problem .. after I submit the form I got order values in Create action BUT files is always NULL !
What I miss
Thanks in advance
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(MainContext model)
{
// here fetch values from model.Order and model.File
}
Instead of fetching two models separately call "MainContext" class in post action, from that you can get all the view values....

Update List from other class

I have a MVC Application with Index and Detail view. Index show _peticiones list items. And I want to update this list from Detail view.
Detail View
#using (Html.BeginForm())
{
<div class="form-group">
<label for="id">Id:</label>
#Html.TextBoxFor(m => m.Id, new { #id = "id", #class = "form-control", #readonly = "readonly" })
</div>
<div class="form-group">
<label for="nombre">Nombre:</label>
#Html.TextBoxFor(m => m.Nombre, new { #nombre = "nombre", #class = "form-control"})
</div>
<div class="form-group">
<label for="desc">Descripcion:</label>
#Html.TextBoxFor(m => m.Desc, new { #dec = "desc", #class = "form-control"})
</div>
<div class="form-group">
<label for="fecha">Fecha:</label>
#Html.TextBoxFor(m => m.Fecha, new { #fecha = "fecha", #class = "form-control"})
</div>
<div class="form-group">
<label for="activo">Activo:</label>
#Html.TextBoxFor(m => m.Activo, new { #activo= "activo", #class = "form-control" })
</div>
<div class="container-fluid">
<div class="col-md-12 text-right">
<input type="submit" value="Guardar" class="btn btn-primary" />
</div>
</div>
}
Controller (Update method has "id" as parameter, i can't use object like a parameter)
public ActionResult Detail(Peticion peticion)
{
if (ModelState.IsValid)
{
var id = peticion.Id;
_peticionService.Update(id);
return RedirectToAction("Index");
}
return View();
}
Class PeticionService
public bool Update(int id)
{
if (id > 0)
{
var peticionOld = _peticiones.FirstOrDefault(u => u.Id == id);
if (peticionOld != null)
{
//How to update item list??
return true;
}
}
return false;
}
How can I update list from "PeticionService" class with just id?
I would approach your problem like the below.
Create a view model for your view.
public class PeticoneViewModel
{
public Peticione CurrentPeticione { get; set; }
}
Then have a service that handles the retrieval and updates to the list source.
public class PeticoneService
{
public Peticione GetPeticioneByID(int id)
{
//Put your implementation here.
return new Peticione();
}
public bool SavePeticioneByID(int id, string newValue)
{
//Put your implementation here.
return true;
}
}
Then create a controller to return the Detail view and handle the update
public class PeticioneController : Controller
{
public ActionResult Detail(int peticonID)
{
var peticoneService = new PeticoneService();
var peticoneViewModel = new PeticoneViewModel();
peticoneViewModel.CurrentPeticione = peticoneService.GetPeticioneByID(peticonID);
return View("Detail",peticoneViewModel);
}
public bool UpdatePeticone(int id, string newValue)
{
if (id > 0)
{
var peticoneService = new PeticoneService();
return peticoneService.SavePeticioneByID(id, newValue);
}
return false;
}
}
Also in an ideal world your service should be injected into the controller so the controller isn't responsible for the service instantiation. But that's another issue.
Hope the above helps.

HttpPostedFileBase to varbinary(max)

I have just tried a lot of things that I found but at the end nothing successfull.
First I have the next code that just do the things ok but dont save the image.
What should I do to save an image into a varbinarymax? and how to show them to the view next?
view:
<div class="form-group">
#Html.LabelFor(model => model.Logo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.EditorFor(model => model.Logo, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.TextBoxFor(model => model.Logo, new { type = "file" })
#Html.ValidationMessageFor(model => model.Logo, "", new { #class = "text-danger" })
</div>
</div>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,Name,Address,Description,Mail,Phone,Small_Description")] School school)
{
if (ModelState.IsValid)
{
db.School.Add(school);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(school);
}
Model:
public partial class School
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public School()
{
this.Product = new HashSet<Product>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Description { get; set; }
public string Mail { get; set; }
public int? Phone { get; set; }
public byte[] Logo { get; set; }
public string Small_Description { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Product> Product { get; set; }
}
Change View First to This:
#using (Html.BeginForm("Create", "Schole", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
#Html.LabelFor(model => model.Logo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Logo, new { type = "file" })
<input type="submit" value="submit" />
</div>
</div>
}
Change Action To This:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,Name,Address,Description,Mail,Phone,Small_Description")] School school, HttpPostedFileBase Logo)
{
if (ModelState.IsValid)
{
using (var memoryStream = new MemoryStream())
{
Logo.InputStream.CopyTo(memoryStream);
school.Logo = memoryStream.ToArray();
}
db.School.Add(school);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(school);
}
}
Now This Logo Save It.
As you don't have posted complete form, here is complete code to upload image and save into DB.
you form must have enctype property.
#using (Html.BeginForm("Index","Home",FormMethod.Post, new{ enctype = "multipart/form-data" }))
{
//your other code
<input type="file" name="logo" />
<input type="submit" value="Save" />
}
And inside your action.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,Name,Address,Description,Mail,Phone,Small_Description")] School school)
{
if (ModelState.IsValid)
{
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files["logo"].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files["logo"].ContentLength);
}
school.Logo=fileData;
db.School.Add(school);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(school);
}
It will save file in your Db.

Categories

Resources