This is my first post so please be gently.. I'm using vs 2017,asp.net core 2.2 I have problem with method to save object in db menaging ViewModel using repository pattern. Im trying to save id from table Category in table Offers using by VM. I would like to the Category in Offers view was display as NameCategory in DropDownList, and save value Id to Offers table. This is my files:
class:
public class Offers
{
public int Id { get; set; }
public string Title{ get; set; }
public string Contents{ get; set; }
public int CategoryId { get; set; }
public Category Categorys { get; set; }
public string PicturePath { get; set; }
}
public class Category
{
[Key]
public int CategoryId { get; set; }
public string NameCategory { get; set; }
public IEnumerable<Offers> OffersList { get; set; }
}
ViewModel:
public class OffeersVM
{
public string Title { get; set; }
public string Content { get; set; }
public Category Category{get;set;}
public List<IFormFile> Picture { get; set; }
}
controller:
[HttpPost]
public IActionResult Create(OffeersVM model)
{
if (ModelState.IsValid)
{
string uniqueName = ProcesEditPicture(model);
Offers newOffers = new Offers
{
Title= model.Title,
Content = model.Content,
CategoryId = model.Category,//I think this is not corect...
PicturePath = uniqueName
};
_offer.Add(newOffers);
return RedirectToAction("details", new { id = newOffers.Id });
}
return View();
}
view:
@model OffeersVM
@{
ViewBag.Title = "Add offer.";
}
<form asp-controller="Home" asp-action="Create" method="post" enctype="multipart/form-data">
<div class="form-group">
<label asp-for="Title">Title</label>
<input asp-for="Title" class="form-control" id="exampleFormControlInput1" placeholder="Title">
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">Select category.</label>
<select class="form-control" id="exampleFormControlSelect1" asp-for="Category" asp-items="@*I't know what item...?*@">
<option value=" test">Please select category.</option>
</select>
<span asp-validation-for="Category"></span>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1" asp-for="Content">Content offer.</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="6" asp-for="Content"></textarea>
<span asp-validation-for="Content" class="text-danger"></span>
</div>
<div class="form-group">
<div class="col-sm-10">
<div class="custom-file">
<input multiple asp-for="Picture" class="form-control custom-file-input " />
<label class="custom-file-label ">Picture</label>
</div>
</div>
</div>
<div>
<button type="submit" class="btn btn-outline-success">Add offer</button>
</div>
</form>
I do't know how to use SelectList or List to provide Id Category. If enybody know some good turtorials with repository pater , or (better) can help to solve my problem I'll be wery grateful. Adam.
P.S Sorry about my English...