我想在数据库中添加新闻。当我使用此代码进行选择类别返回
时我是空的。我该如何解决这个问题?
<select name="category">
@{
foreach (var item in RCat.MainCategory().Where(a=>a.ParentID==1))
{
<option value="@item.ID">@item.Title</option>
}
}
</select>
我的控制器:
[HttpPost]
[ValidateInput(false)]
public ActionResult CreateNews(Tbl_News t, HttpPostedFileBase pic, int Category)
{
try
{
if (Session["Username"] == null)
return RedirectToAction("Register", "Home");
if (pic == null)
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . باید عکسی را برای خبر انتخاب کنید";
return View();
}
if (Category == 0)
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . باید یکی از دسته ها را انتخاب کنید";
return View();
}
t.Date = DateTime.Now.Date;
t.Dislike = 0;
t.Like = 0;
t.Visit = 0;
t.Username = Session["Username"].ToString();
if (t.Type != "iran" && t.Type != "world" && t.Type != "sport" && t.Type != "art" && t.Type != "knowledge" && t.Type != "economic" && t.Type != "memo" && t.Type != "you" && t.Type != "pic" && t.Type != "video")
t.Type = null;
if (ModelState.IsValid)
{
if (pic != null)
{
if (pic.ContentLength <= 512000)
{
if (pic.ContentType == "image/jpeg")
{
Random rnd = new Random();
string picname = rnd.Next().ToString();
string path = System.IO.Path.Combine(Server.MapPath("~/Content/img/NewsPic/"));
pic.SaveAs(path + picname);
t.Image = picname;
db.Tbl_News.Add(t);
if (Convert.ToBoolean(db.SaveChanges()))
{
var q = (from a in db.Tbl_News
orderby a.Date descending
select a).FirstOrDefault();
Tbl_Cat_News TCN = new Tbl_Cat_News();
TCN.NewsID = q.ID;
TCN.CatID = Category;
db.Tbl_Cat_News.Add(TCN);
if (Convert.ToBoolean(db.SaveChanges()))
{
ViewBag.Style = "color:green";
ViewBag.Message = "با موفقیت ثبت شد";
return View();
}
else
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . خبر ثبت نشد";
return View();
}
}
else
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . خبر ثبت نشد";
return View();
}
}
else
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . فرمت تصویر باید jpg باشد";
return View();
}
}
else
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . حجم تصویر باید بیشتر کمتر از 515 کیلو بایت باشد";
return View();
}
}
else
{
return RedirectToAction("Logout", "Admin");
}
}
else
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . تمامی فیلدها باید پر شوند";
return View();
}
}
catch (Exception)
{
return Content("خطا");
}
}
答案 0 :(得分:0)
您拥有所有 OR 条件,因此如果任何类型不匹配且任何条件,则会触发“t.Type = null;”因此,你总是得到“NULL”值。