How to upload form contents with a file to database? - asp.net-mvc

This is my code,i have also tried strongly typed view but i it does not create an upload field
#Model
namespace master_layout.Models
{
[Table("Candidates")]
public class Candidate
{
[Key]
public int CandidateID { get; set; }
public string FirstName { get; set; }
public string LastName{get;set;}
public DateTime Date{get;set;}
public string EmailID{get;set;}
public long ContactNumber{get;set;}
public long AlternateContactNumber{get;set;}
public int RecruitmentStatusID{get;set;}
public DateTime CreatedOn{get;set;}
public DateTime LastUpdatedOn{get;set;}
public byte[] Resume { get; set; }
}
public class CandidateContext : DbContext
{
public DbSet<Candidate> Candidates { get; set; }
}
The following is my controller code
Controller:
namespace proedit1.Controllers
{
public class HomeController : Controller
{
CandidateContext db = new CandidateContext();
public ActionResult Index()
{
return View(db.Candidates.ToList());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Candidate candidate)
{
if (ModelState.IsValid)
{
db.Candidates.Add(candidate);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View(candidate);
}
}
}
View:
#using (Html.BeginForm("Newcandidate", "CandidatesController", FormMethod.Post, new { EncType="multipart/form-data"}))
{
<table class="navbar-form">
<tr>
<th>First Name<input type="text" placeholder="Your First Name" class="margin"/></th>
</tr>
<tr>
<th>Last Name<input type="text" placeholder="Your Last Name"/></th>
</tr>
<tr>
<th>Date of Birth <input type="date" name="db" /></th>
</tr>
<tr>
<th>E-Mail ID<input type="email" placeholder="abc#yourserviceprovider.com" /></th>
</tr>
<tr>
<th>Contact No<input type="tel" placeholder="04426506555 or 98414981414" min="8" maxlength="10"/></th>
<tr>
<tr>
<th>Alternate No <input type="tel" placeholder="04426506555 or 98414981414" min="8" maxlength="10"/></th>
<tr>
<th>Created On <input type="date" /></th>
<tr>
<th>Updated On <input type="date" /></th>
</tr>
<tr>
<th> <input type="file" placeholder="your resume in ms.word format" accept="application/msword" name="NamebtnUpload"/>
</th></tr>
</table>
<div class="row">
<div class="span4">
<input type="submit" class="btn-success" value="UPLOAD" name="Submit"/>
<input type="reset" class="btn-warning" name="Reset" />
</div>
</div>
}
I am a newbie in MVC pls provide me with the correct code to upload details to my database

There is a solution which are you looking for:
MVC 4 Razor File Upload
Create new view model for your 'view'. Don't use entity model, please.

Related

Input box as “date” on web when model is “int” (again)

I decided to create a new post here instead of the other post which was a bit confusing. (Input box as "date" on web when model is "int")
In this post I have added the code I use.
The problem is that in the SQL server the field FrDr is of type int and I need the user on the webpage to enter in a input field of type "date"
If I add [DataType(DataType.Date)] to the model i get the input date type autmoatically. but not if I add it to the Page Model
How can I change my code so that the user get an input field of type date that save the date value as an int to SQL.
MODEL AGR.CS
namespace DateTest.VismaModels {
public partial class Agr {
[Key]
[Display(Name = "Actor")]
public int AgrActNo { get; set; }
public int AgrNo { get; set; }
[DataType(DataType.Date)]
[Display(Name = "From Date")]
public int FrDt { get; set; }
}
}
PAGE MODEL
namespace DateTest.Pages {
public class IndexModel : PageModel {
private readonly DateTest.VismaModels.F0001Context _context;
public IndexModel(DateTest.VismaModels.F0001Context context) {
_context = context;
}
public bool ShowMessage => !string.IsNullOrEmpty(Message);
[TempData]
public string Message { get; set; }
[BindProperty]
public Agr AgrRow { get; set; }
public async Task<IActionResult> OnGetAsync(int? id) {
if (id == null) {
Console.WriteLine("New");
AgrRow = new Agr();
AgrRow.AgrNo = _context.Agr.Select(q => q.AgrNo).DefaultIfEmpty(0).Max() + 1;
//AgrRow.FrDt = int.Parse(DateTime.Now.ToString("yyyyMMdd"));
}
if (!ModelState.IsValid) {
//var errors = ModelState.Select(x => x.Value.Errors).Where(y => y.Count > 0).ToList();
var errors = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));
Message += "Model not valid : " + errors;
return Redirect("~/Activities/index");
}
return Page();
}
public async Task<IActionResult> OnPostSaveNewRowAsync() {
if (!ModelState.IsValid) {
//var errors = ModelState.Select(x => x.Value.Errors).Where(y => y.Count > 0).ToList();
var errors = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));
Message += "Model not valid : " + errors;
return Redirect("~/index");
}
_context.Add(AgrRow);
try {
await _context.SaveChangesAsync();
} catch (DbUpdateConcurrencyException) {
throw;
}
Message += "Saved";
return RedirectToPage("/index");
}
}
}
RAZOR PAGE
#page
#model DateTest.Pages.IndexModel
#{
ViewData["Title"] = "Activities";
}
<h2>Activities</h2>
#if (Model.ShowMessage) {<div class="alert alert-info alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"></button>
#Model.Message
</div>
}
<p>
<a asp-page="Create">Create New</a>
</p>
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="AgrRow.AgrNo" />
<table class="table">
<tbody>
<tr>
<td><input asp-for="#Model.AgrRow.AgrActNo" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.FrDt" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.ToDt" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.FrTm" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.ToTm" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.CustNo" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.ProdNo" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.Descr" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.NoInvoAb" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.Price" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.Am" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.Fin" class="form-control" /></td>
<td><input asp-for="#Model.AgrRow.Invo" class="form-control" /></td>
<td>
<div class="form-group">
<button type="submit" value="Save New" asp-page-handler="saveNewRow" asp-route-id="#Model.AgrRow.AgrNo" class="btn btn-default">
<i class="fa fa-save"></i>Create
</button>
</div>
</td>
</tr>
</tbody>
</table>
</form>
UPDATE
If I add the following to the Page Model
public DateTime FrDt { get; set; }
And print out the result in the post method like this
Console.WriteLine("FRDT = " + FrDt);
Console.WriteLine("AGRROW FRDT = " + AgrRow.FrDt);
I get this
FRDT = 0001-01-01 00:00:00
AGRROW FRDT = 0
I figured it out.
In my Agr Model I add a temporary field FrDt2 which is of DateTime and use the [NotMapped] annotation so it does not send it to sql
[NotMapped]
public DateTime FrDt2 { get; set; }
And in my Page model I convert FrDt2 to int before adding it to FrDt.
AgrRow.FrDt = int.Parse(AgrRow.FrDt2.ToString("yyyyMMdd"));
And, to show an existing item from SQL in the input date box I convert it back to int like this
AgrRow.FrDt2 = DateTime.ParseExact(AgrRow.FrDt.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);

Sending table datas to Controller without using ajax

I have a table in view which is static in nature.I am trying to post data to Controller without using Jquery Ajax. Is it possible?How can I retrieve all these data in Action "bulk_insert". I am able to send this bulk data to controller using jquery ajax but I am unable to send it directly.
My view :
#using entity_framework.Models
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<h1>Static data</h1>
<div>
#using (Html.BeginForm("bulk_insert", "Form", FormMethod.Post, new { enctype = "multipart/form-data", id = "postForm" }))
{
<table id="myTable" class="table table-striped">
<thead>
<tr>
<td>Menu Item Id</td>
<td>Menu Item Name</td>
<td>Menu Qty</td>
<td>Menu Rate</td>
<td>Total</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="hidden" name="menu_item_id[0]" value="1" /><span>1</span></td>
<td><input type="hidden" name="menu_item_name[0]" value="chaumin" /><span>chaumin</span></td>
<td><input type="hidden" name="data[0].rate" value="100" /><span>100</span></td>
<td><input type="hidden" name="data[0].qty" value="2" /><span>2</span></td>
<td><input type="hidden" name="data[0].total" value="200"><span>200</span></td>
</tr>
<tr>
<td><input type="hidden" name="data[1].menu_item_id" value="2" /><span>2</span></td>
<td><input type="hidden" name="data[1].menu_item_name" value="Mo:Mo" /><span>Mo:Mo</span></td>
<td><input type="hidden" name="data[1].rate" value="100" /><span>100</span></td>
<td><input type="hidden" name="data[1].qty" value="2" /><span>2</span></td>
<td><input type="hidden" name="data[1].total" value="200"><span>200</span></td>
</tr>
</tbody>
</table>
<input type="submit" value="Submit" />
}
</div>
I am just testing with static data right now,but I need to do it with dynamic data i.e, When a user clicks a button, a row gets added using javascript .So,I didn't use Htmlhelper. My model:
public class tabledata
{
public int menu_item_id { get; set; }
public string menu_item_name { get; set; }
public string rate { get; set; }
public string qty { get; set; }
public string total { get; set; }
}
I don't know how can I get table datas from form but my Controller method:
[HttpPost]
public ActionResult bulk_insert(IEnumerable<tabledata> data)
{
//How can I get table datas here
}

How to get client side generated class list to MVC post action argument?

I have one form where I am generating some control dynamically (Which is list some class . in image add product artwork section) When I click on submit button how can i get this values in post Action method's argument so that I can use this value in collection.
For reference I have attached the image where i have option for multiple Artwork oprion
[HttpPost]
public ActionResult Add(Graphic graphicToAdd,Enumerable<GraphicArtwork> artworkOption)
{
// I want value in artworkOption
}
public class GraphicArtwork
{
[Key]
public int GraphicArtworkId { get; set; }
public int GraphisId { get; set; }
[Required(ErrorMessage = "The {0} is required.")]
[DisplayName("Option Text")]
[StringLength(500)]
public string ArtOptionText { get; set; }
public decimal Price { get; set; }
[DisplayName("Active")]
public bool IsActive { get; set; }
public DateTime CreatedDate { get; set; }
[NotMapped]
public int TotalRecordCount { get; set; }
}
This is my view :
<div class="editor-field PrintOptions">
<table data-bind="visible :customArtworks().length > 0">
<thead>
<tr>
<td class="editor-label">Option</td>
<td class="editor-label">Price</td>
<td></td>
</tr>
</thead>
<tbody data-bind="foreach: customArtworks">
<tr>
<td>
<input placeholder="Enter Artwork Text" type="text" data-bind="value: ArtOptionText'}" />
</td>
<td>
<input placeholder="Enter Price" type="text" data-bind="value: Price" />
</td>
<td>
<img title="Add" src="~/Content/images/icon_add.png">
<img title="Delete" style="margin-left:10px;" src="~/Content/images/icon_delete.png">
</td>
</tr>
</tbody>
</table>
</div>
For more detail : I am generating my dynamical control using knockout.js
// Ko Implemntation
function GraphicArtwork(ArtOptionText, Price) {
var self = this;
self.ArtOptionText = ArtOptionText;
self.Price = Price;
self.formattedPrice = ko.computed(function () {
var price = self.Price;
return price ? "$" + price.toFixed(2) : "0.00";
})
}
function GraphicArtworkViewModel() {
var self = this;
self.customArtworks = ko.observableArray([GraphicArtwork(null, null)]);
self.add = function () {
self.customArtworks.push(new GraphicArtwork(null, null));
};
self.remove = function (GraphicArtwork) {
self.customArtworks.remove(GraphicArtwork);
};
}
ko.applyBindings(new GraphicArtworkViewModel());
Add This binding :
<td>
<input placeholder="Enter Artwork Text" type="text" data-bind="value: ArtOptionText,attr:{name: '['+$index()+'].ArtOptionText'}" />
</td>
<td>
<input placeholder="Enter Price" type="text" data-bind="value: Price,attr:{name: '['+$index()+'].Price'}" />
</td>
AND in Code Behind
public ActionResult Add(Graphic graphicToAdd,IEnumerable<GraphicArtwork> listOfGraphicArtwork)
{
// listOfGraphicArtwork will hold all the required data
}

When i set value of elements in editor template for grid pop up create , posting to controller as null

in my view there are two grid. when i select a row in first grid, second one is binding according to first one.
what i want to do is take common parameters from first one, used in second one create template in readonly or disabled inputs. my problem is input elements take parameter from first grid but, dont post to controller.
Controller Function
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult DonemKursSinifiOlustur([DataSourceRequest] DataSourceRequest request, DonemKursSinifi model,string DonemId, string DersId, string EgitmenId )
{
if (model != null && ModelState.IsValid)
{
Helper.Islemci.DonemKursSinifiTanimla(model);
}
return Json(new[] { model }.ToDataSourceResult(request, ModelState));
}
model.DonemId, model.DersId, model.EgitmenId and DonemId, DersId, EgitmenId come null.
EditorTemplate View for Grid Create and Update
#model Kurslar.Models.DonemKursSinifi
#using (Html.BeginForm("DonemKursSinifiOlustur","Tanim",FormMethod.Post))
{
<table>
<tr>
<td>
Lütfen Gün ve Saati Belirtiniz:
</td>
<td>
#Html.Kendo().AutoCompleteFor(m=>m.Tanim)
</td>
</tr>
<tr>
<td>
Donem :
</td>
<td>
#Html.Kendo().AutoCompleteFor(m=>m.DonemBaslangicBitis)
#Html.HiddenFor(m => m.DonemId)
</td>
</tr>
<tr>
<td>
Ders Adı:
</td>
<td>
#Html.Kendo().AutoCompleteFor(m=>m.DersAdi)
#Html.HiddenFor(m => m.DersId)
</td>
</tr>
<tr>
<td>
Eğitmen
</td>
<td>
#Html.Kendo().AutoCompleteFor(m=>m.EgitmenAdiSoyadi)
#Html.HiddenFor(m => m.DonemId)
</td>
</tr>
</table>}
First AutoCompleteFor works correctly because take input from user, not before setted.
*and my javaScript code to fill parameters to EditorTemplate *
and it works fine
var grid = $("#donemGrid").data("kendoGrid");
var rows = grid.select();
alert(rows);
try {
var donemID = grid.dataItem(rows).DonemId;
var dersID = grid.dataItem(rows).DersId;
var egitmenID = grid.dataItem(rows).EgitmenId;
var dersAdi = grid.dataItem(rows).DersAdi;
var egitmenAdiSoyadi= grid.dataItem(rows).EgitmenAdiSoyadi;
var donemBaslangicBitis = grid.dataItem(rows).DonemBaslangicBitis;
} catch (e) {
alert(e);
}
$("#DonemBaslangicBitis").data("kendoAutoComplete").value(donemBaslangicBitis);
$("#DersAdi").data("kendoAutoComplete").value(dersAdi);
$("#EgitmenAdiSoyadi").data("kendoAutoComplete").value(egitmenAdiSoyadi);
$("#DonemId").val(donemID);
$("#DersId").val(dersID);
$("#EgitmenId").val(egitmenID);
*if needed, my model *
public class DonemKursSinifi
{
[Key]
[Required]
[PersistentProperty(IsAutoIncremented = true)]
public int Id { get; set; }
[PersistentProperty]
public string Tanim { get; set; }
[PersistentProperty]
public int DonemId { get; set; }
[PersistentProperty]
public int DersId { get; set; }
[PersistentProperty]
public int EgitmenId { get; set; }
[PersistentProperty]
public int KontenjanSayisi { get; set; }
[PersistentProperty]
public int TarifeId { get; set; }
[PersistentProperty]
public int IslemNo { get; set; } // default 1
public string EgitmenAdiSoyadi { get; set; }
public string DersAdi { get; set; }
public string DonemBaslangicBitis { get; set; }
}
ok, probably you have repeated the id in the grid and also have the same name attributes in the same form to do this:
#Html.HiddenFor(m => m.DersId)
mabe you can do somethin like this:
form:
#model Kurslar.Models.DonemKursSinifi
#using (Html.BeginForm("DonemKursSinifiOlustur","Tanim", FormMethod.Post, new { id="myform"}))
{
<input type="hidden" value="" name="Tanim" />
<input type="hidden" value="" name="DonemBaslangicBitis" />
<input type="hidden" value="" name="DonemId" />
<input type="hidden" value="" name="DersAdi" />
<input type="hidden" value="" name="DersId" />
<input type="hidden" value="" name="EgitmenAdiSoyadi" />
<input type="hidden" value="" name="DonemId" />
}
table:
<table>
<tr>
<td>Lütfen Gün ve Saati Belirtiniz:</td>
<td>#Html.Kendo().AutoCompleteFor(m=>m.Tanim)</td>
</tr>
<tr>
<td>Donem :</td>
<td>#Html.Kendo().AutoCompleteFor(m=>m.DonemBaslangicBitis) #Html.HiddenFor(m => m.DonemId)</td>
</tr>
<tr>
<td>Ders Adı:</td>
<td>#Html.Kendo().AutoCompleteFor(m=>m.DersAdi) #Html.HiddenFor(m => m.DersId)</td>
</tr>
<tr>
<td>Eğitmen</td>
<td>#Html.Kendo().AutoCompleteFor(m=>m.EgitmenAdiSoyadi) #Html.HiddenFor(m => m.DonemId)</td>
</tr>
</table>
js:
var
grid = $("#donemGrid").data("kendoGrid"),
rows = grid.select(),
form = $('#myform');
form.find('input[name="DonemBaslangicBitis"]').val(grid.dataItem(rows).DonemBaslangicBitis);
form.find('input[name="DersAdi"]').val(grid.dataItem(rows).DersAdi);
form.find('input[name="EgitmenAdiSoyadi"]').val(grid.dataItem(rows).EgitmenAdiSoyadi);
form.find('input[name="DonemId"]').val(grid.dataItem(rows).DonemId);
form.find('input[name="DersId"]').val(grid.dataItem(rows).DersId);
form.find('input[name="EgitmenId"]').val(grid.dataItem(rows).EgitmenId);
form.submit();

Passing back child entity from MVC view to controller

I'm trying to delete entries which are marked (checked) in view, but not sure how to pass back the collection back to the controller
my mode is:
Group which has ICollection<SubGroup> SubGroups and SubGroup has ICollection<Event> Events
I pass Group to the view and iterate and display Event details including a checkbox so if it's checked the event entry should be deleted.
When I get the postback to the controller, Group.SubGroups is null
How do I make sure the child entities are passed back to the controller?
Can I use #Html.CheckBox instead Of <input type="checkbox"... ?
Update: Model
public class Group
{
[Key]
public int GroupId { get; set; }
public virtual IList<SubGroup> SubGroups { get; set; }
....
}
public class SubGroup
{
[Key]
public int SubGroupId { get; set; }
public virtual IList<Event> Events { get; set; }
....
}
public class Events
{
[Key]
public int EventId { get; set; }
public string EventName { get; set; }
public bool IsDeleted { get; set; }
....
}
I am passing Group to the view (see below) as the Model and want to delete events which are checked by the user
View:
#using System.Globalization
#model NS.Models.Group
#{
ViewBag.Title = "Edit";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Booking Details</legend>
<div class="display-label">
Group Name
</div>
<div class="display-field">
#Html.DisplayFor(model => model.GroupName)
</div>
<div class="display-field">
#foreach (var b in Model.SubGroup)
{
groupNo += 1;
<table class="main" style="width: 80%; margin-top: 10px">
<tr>
<th>
#Html.DisplayName("Sub Group ")
#Html.DisplayName(b.SubGroupName)
</th>
</tr>
<table class="main" style="width: 80%;">
<tr>
<th>Event</th>
<th>Delete</th>
</tr>
#foreach (var ev in b.Events)
{
<tr>
<td>
#Html.DisplayFor(modelItem => ev.EventName)
</td>
<td>
<input type="checkbox" id="eventToDelete" name="eventToDelete" value="#ev.EventId" />
</td>
</tr>
}
</table>
</table>
}
</div>
<p>
<input type="submit" name="xc" value="Delete" class="button" />
</p>
</fieldset>
}
Thank You
Try this...
public ActionResult ViewName(FormCollection collection)
{
if(collection['eventToDelete']!=null && collection['eventToDelete'].ToString()!="")
{
//delete....
}
return....
}
Try this
public ActionResult ViewName(Group model)
{
if(model != null && ModelState.IsValid)
{
//delete....
}
return....
}

Resources