繁体   English   中英

从控制器asp.net mvc中的给定ID获取数据

[英]fetch data from the given id in the controller asp.net mvc

在我的情况下,添加业务时,我需要从数据库中获取保存到该数据库的字符串。 我能够通过业务控制器中的以下代码将其保存到数据库

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,Title,Address,Category,Description,Latitude,Longitute,Owner")] Business business)
    {
        business.Owner = System.Web.HttpContext.Current.User.Identity.Name;//I'm saving the current user as the owner
        if (ModelState.IsValid)
        {
            db.Businesses.Add(business);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(business);
    }

现在,我需要做的就是检查当前用户用户是否是该企业的所有者,如上面的代码所示,当添加企业时,该用户将保存在模型中。 模型类在下面

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebPortal.Models
{
    public class Business
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public string Address { get; set; }
        public string Category { get; set; }
        public string Description { get; set; }
        public double Latitude { get; set; }
        public double Longitude { get; set; }    
        public string Owner { get; set; }//in order to detect the original creator of the businness
    }
}

保存部分工作正常,这是我尝试在业务控制器中获取的代码

// GET: Businesses/Edit/5
    [Authorize]
    public ActionResult Edit([Bind(Include = "ID,Title,Address,Category,Description,Latitude,Longitute,Owner")] int? id, string ownerr, Business business)
    {
        Business bs = new Business();
        //Authorizing Edit permission only for the owner of the business and the admin
        if (!((System.Web.HttpContext.Current.User.Identity.Name == bs.Owner
                || User.Identity.Name == "admin@gmail.com" )))
        {
            return View(db.Businesses.ToList());
        }

有点不对劲。 我只需要知道如何通过传递ID来获取业务的相关所有者...

编辑

可以通过以下html获取ID,我也尝试通过owner ,但它在控制器中返回null

{
            @Html.ActionLink("| Edit | ", "Edit", new { id = item.ID, owner = item.Owner }) 
            @Html.ActionLink("Delete", "Delete", new { id = item.ID })
        }

我通常将身份ID用作模型的ID,然后使用ApplicationUserManager来查询数据库中当前登录的用户

 private ApplicationUserManager _userManager;
          public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }


var user =  UserManager.FindById(User.Identity.GetUserId());
var userId = Guid.Parse(user.Id);

var _context = new MessageContext();               
var myContacts = _context.Contacts.Where(c => c.CustomerId == userId).ToList();
                 ViewBag.Contacts = myContacts;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM