简体   繁体   中英

Insert SQL to LINQ data into input form

How can I insert data into this form field. So I have my fancy looking form, and I want to add two values that I queried from the database into this.

HTML view:

@model CWebPortal.Models.onboard_test
    @using (Html.BeginForm("Results", "OnBoarding", FormMethod.Post))
                    {
                        <form>
 <div class="row">
  <div class="input-group input-group-icon1">
  <input type="text" placeholder="Project Name" name="projectname" value = "" required />
  <div class="input-icon"><i class="fa fa-user" style="padding-top:20px;"></i> Project Name</div>
  </div>
  <div class="input-group input-group-icon1">
  <input type="text" placeholder="Developer" name="developer" />
  <div class="input-icon"><i class="fa fa-file-text" style="padding-top:20px"></i> Developer</div>
    </div>
    </div>
    </form>

}

Controller with LINQ:

        var DataContext = new BalanceDataContext();
        var custQuery2 = (from m in DataContext.onboard_tests
                           orderby m.date_created descending
                           select m).Take(1);
        return View(custQuery2);

Model:

public class Onboard
{
    [Key]
    public Guid projectID { get; set; }
    [Required]
    public string ProjectName { get; set; }
    [Required]
    public string Developer { get; set; }
    public DateTime date_created { get; set; }
}

I want to just be like:

<input type="text" placeholder="Project Name" name="projectname" value = "@model.projectname" required />

Since I am not doing this the @Html.DisplayNameFor(model => model.projectname) method.

Thanks for the help guys.

Instead of .Take(1) you should use FirstOrDefault() .

Explanation: your view has model of type CWebPortal.Models.onboard_test . But LINQ operator Take returns a query of IQueryable<CWebPortal.Models.onboard_test> type no matter if you'll specify 10 entities or 1 entity. In order to get single entity (as your view expects) you should execute query and get single entity. Best way to do that is FirstOrDefault() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM