如何将带有文件的表单内容上传到数据库?

时间:2014-02-25 10:34:12

标签: asp.net-mvc database file-upload

这是我的代码,我也尝试过强类型视图,但我没有创建上传字段

   #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; }

}


以下是我的控制器代码     

 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&nbsp;<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&nbsp;<input type="tel" placeholder="04426506555 or 98414981414" min="8" maxlength="10"/></th>
  <tr>
  <th>Created On&nbsp;<input type="date" /></th>

  <tr>
  <th>Updated On&nbsp;&nbsp;<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>
}

我是MVC的新手,请为我提供正确的代码,将详细信息上传到我的数据库

1 个答案:

答案 0 :(得分:0)

您正在寻找解决方案:

MVC 4 Razor File Upload

为“视图”创建新的视图模型。 Don't use entity model ,拜托。