ورود

View Full Version : سوال: اضافه کردن یک user به پایگاه داده در صورتی که از viewmodel استفاده میکنیم



speralda
دوشنبه 09 دی 1392, 15:26 عصر
درود دوستان

من یک viewmodel دارم که سه proprty درونش هست(user,product,productgroup)

یک view دارم برای عضویت کاربر که این view هم داره از layouty استفاده میکنه که در آن (productgroup) هست

سوال من اینجاست که به چه نحوی viewmodel رو بنویسم و چگونه کاربر اضافه کنم وقتی داره از این modelview استفاده میکنه.

من modelview رو این طوری نوشتم


public class HomeContent
{
public IEnumerable<Products> Productses { get; set; }
public IEnumerable<ProductGroups> ProductGroupses { get; set; }
public IEnumerable<Users> Userses { get; set; }
}


برای controller


public ActionResult CreateAccount(HomeContent users)
{
if (ModelState.IsValid)
{

db.Userse.Add(users);
db.SaveChanges();
return RedirectToAction("CreateAccountSuccess");
}

return View(users);
}



ولی به users این خط اررور میده

db.Userse.Add(users);


ممنون میشم راهنمایی کنید.

speralda
جمعه 13 دی 1392, 21:35 عصر
حل شد.

در viewmodel


namespace Eshop.ViewModel
{
public class HomeContent
{
public IEnumerable<Products> Productses { get; set; }
public IEnumerable<ProductGroups> ProductGroupses { get; set; }
public Users Userses { get; set; }
public Products Products { get; set; }
public ProductGroups ProductGroups { get; set; }
}

}


در controller


[HttpPost]
public ActionResult CreateAccount(HomeContent users)
{

if (ModelState.IsValid)
{
db.Userse.Add(users.Userses);
db.SaveChanges();
return RedirectToAction(&quot;CreateAccountSuccess&quot;);
}
else
{
ModelState.AddModelError(&quot;&quot;, &quot;ثبت نام انجام نشد&quot;);
}

var products = db.Products.ToList();
var productGroups = db.ProductGroups.ToList();
var model = new HomeContent
{
Productses = products,
ProductGroupses = productGroups,

};
return View(model);
}


در view CreateAccount
یک تیکه از کد


@model Eshop_SportS.ViewModel.HomeContent
@{
ViewBag.Title = &quot;CreateAccount&quot;;
Layout = &quot;~/Views/Users/_LayoutUsers.cshtml&quot;;
}
<table align=&quot;center&quot; cellpadding=&quot;3&quot; cellspacing=&quot;8&quot; class=&quot;tbl&quot;>
<tr>
<td align=&quot;right&quot; class=&quot;tr&quot;>
@Html.LabelFor(model => model.Userses.UserName):
</td>
<td align=&quot;right&quot; class=&quot;tr&quot;>
@Html.EditorFor(model => model.Userses.UserName)
<label class=&quot;inputRequirement&quot;>
*</label>
@Html.ValidationMessageFor(model => model.Userses.UserName)
</td>
</tr>
<tr>
....
...

Cybersilent
شنبه 14 دی 1392, 11:16 صبح
راه حل درست اینه که با استفاده از ابزار AutoMapper کلاس ViewModel خودتون رو به کلاس model اصلی که در بانک اطلاعاتی هست، کپی کنید.
درباره AutoMapper جستجو کنید.