【发布时间】:2019-11-21 04:48:04
【问题描述】:
我想在当前操作发生时将 bool 的状态更改为 true。操作结果从剃刀页面获取 id,然后在我的站点地图中创建一个链接。当它这样做时,我希望它改变记录中布尔的状态并保存它。我尝试在控制器中实现此代码,但没有成功。
var isadded = db.Sitemaps.Where(m => m.IsAdded == false).FirstOrDefault();
isadded.IsAdded = true;
这不起作用,因为它不知道应该更改什么记录并且没有保存。
我的代码中已经有这个了。
public ActionResult AddNewSitemapElement(int? id)
然后我确保它不为空,如果是则返回一个 badRequest。然后我有下面的代码可以在整个动作中使用。
MySitemap mySitemap = db.Sitemaps.Find(id);
有没有办法在字符串中使用 id 来改变它?我还应该把它放在操作的底部,以便在将数据添加到 XML 之后执行它还是无关紧要?
感谢您的帮助!
更新:
我将此代码块添加到操作中,它似乎可以工作。从下面的评论建议。在这种情况发生之前,我已经知道 bool 的状态。此布尔值仅控制按钮的显示,以在视图中添加指向 XML 的链接。因此,一旦在数据库中创建了该按钮,就可以将其添加到 xml 中。所以我知道它已经是假的了。然而,这似乎工作。很高兴知道这是否是最好的方法。
if (mySitemap.IsAdded == false) {
mySitemap.IsAdded = true;
db.SaveChanges();
}
更新: 下面是我的完整控制器动作。它按原样工作。如果有更合适的方法来实现这一点,请随时发表评论。
public ActionResult AddNewSitemapElement(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
MySitemap mySitemap = db.Sitemaps.Find(id);
if (mySitemap.IsAdded == false) {
mySitemap.IsAdded = true;
db.SaveChanges();
}
SitemapGenerator sg = new SitemapGenerator();
//create a sitemap item
//var siteMapItem = new SitemapItem(Url.Action("NewAdded", "NewController"), changeFrequency: SitemapChangeFrequency.Always, priority: 1.0);
var siteMapItem = new SitemapItem(PathUtils.CombinePaths(Request.Url.GetLeftPart(UriPartial.Authority), "/" + mySitemap.Category + "/" + mySitemap.Location),
changeFrequency: SitemapChangeFrequency.Daily, priority: (mySitemap.Priority), lastModified: (mySitemap.LastModified));
//Get the XElement from SitemapGenerator.CreateItemElement
var NewItem = sg.CreateItemElement(siteMapItem);
//create XMLdocument element to add the new node in the file
XmlDocument document = new XmlDocument();
//load the already created XML file
document.Load(Server.MapPath("~/Sitemap.xml"));
//convert XElement into XmlElement
XmlElement childElement = document.ReadNode(NewItem.CreateReader()) as XmlElement;
XmlNode parentNode = document.SelectSingleNode("urlset");
//This line of code get's urlset with it's last child and append the new Child just before the last child
document.GetElementsByTagName("urlset")[0].InsertBefore(childElement, document.GetElementsByTagName("urlset")[0].LastChild);
//save the updated file
document.Save(Server.MapPath("~/Sitemap.xml"));
return RedirectToAction("Index", "Sitemap");
}
【问题讨论】:
-
第一块代码是用
AddNewSitemapElementaction方法写的?为什么不检查mySitemap.IsAdded是否为假并将其更改为真?
标签: c# asp.net-mvc