gpt4 book ai didi

asp.net - 保存数据而不是添加到数据库

转载 作者:行者123 更新时间:2023-11-29 13:39:01 25 4
gpt4 key购买 nike

我正在尝试编辑我的 asp.net mvc 项目中的一篇文章。这就是我创建项目时所做的事情:

public ActionResult Create(ArticleViewModel model)
{
if (ModelState.IsValid)
{
try
{
// Get the userID who created the article
User usr = userrepo.FindByUsername(User.Identity.Name);
model.UsernameID = usr.user_id;

repository.AddArticle(model.Title, model.Description, model.ArticleBody);
}
catch (ArgumentException ae)
{
ModelState.AddModelError("", ae.Message);
}

return RedirectToAction("Index");

}

return View(model);
}

在我的存储库中:

public void AddArticle(string Title, string Description, string ArticleBody)
{
item Item = new item()
{
item_title = Title,
item_description = Description,
article_body = ArticleBody,
item_createddate = DateTime.Now,
item_approved = false,
user_id = 1,
district_id = 2,
link = "",
type = GetType("Article")
};

try
{
AddItem(Item);
}

catch (ArgumentException ae)
{
throw ae;
}
catch (Exception)
{
throw new ArgumentException("The authentication provider returned an error. Please verify your entry and try again. " +
"If the problem persists, please contact your system administrator.");
}

Save();
// Immediately persist the User data

}

public void AddItem(item item)
{
entities.items.Add(item);
}

但是现在我想编辑一篇文章,这是我现在所拥有的:

public ActionResult Edit(int id)
{
var model = repository.GetArticleDetails(id);
return View(model.ToList());
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ArticleViewModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the User
try
{
item Item = repository.GetArticleDetailsByTitle(model.Title);

Item.item_title = model.Title;
Item.item_description = model.Description;
Item.article_body = model.ArticleBody.

// HERE I NEED TO SAVE THE NEW DATA

return RedirectToAction("Index", "Home");
}
catch (ArgumentException ae)
{
ModelState.AddModelError("", ae.Message);
}
}

// If we got this far, something failed, redisplay form
return View(model);
}

如您所见,我检查了调整后的文本并将其放入“项目”中。但我怎样才能将其保存在我的数据库中呢? (我的存储库中的函数)

最佳答案

我认为您的 save() 方法有 entityobject.SaveChanches()

所以你想在这里调用 save() 方法

try
{
item Item = repository.GetArticleDetailsByTitle(model.Title);

Item.item_title = model.Title;
Item.item_description = model.Description;
Item.article_body = model.ArticleBody.
**Save();**
return RedirectToAction("Index", "Home");
}
  • 应该只需要Save()方法,而不需要AddItem()方法。

关于asp.net - 保存数据而不是添加到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18368643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com