2017-12-02 13 views
1

我需要從數據庫中獲取一個字符串,在我的案例中添加業務時將其保存到該數據庫中。我可以通過下面的代碼,將其保存到數據庫中的業務控制器從控制器asp.net中的給定ID獲取數據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 == "[email protected]"))) 
     { 
      return View(db.Businesses.ToList()); 
     } 

它還挺wronge獲取代碼。我只需要知道通過傳遞也許是ID如何獲取企業的relavent所有者...

編輯

ID可以通過以下HTML獲取和我正在試圖通過owner以及但是它在控制器返回一個空

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

回答

2

我一般都身份標識模型的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; 
+0

hi @frank獲取id完全沒有問題,只需通過問題底部的編輯代碼即可完成。我需要的只是爲每個ID獲得相關「所有者」... –

+0

您是否擁有所有者模型? –

+0

'owner'是上面提到的'Business'模型的一個屬性... –

相關問題