How to get Kendo Dropdown selected should fill Kendo grid - asp.net-mvc-4

I tried this but from my controller data is returning but not binding to kendo grid
This is my controller
public ActionResult Index(string LocationId)
{
using (var client = new HttpClient())
{
IList<AssetsByLocation> _assetCompanyDetailslist;
AssetRepository assetrep = new AssetRepository();
Guid LocationID = new Guid();
if (Request.Params["LocationId"] != null)
{
LocationID = new Guid(Request.Params["LocationId"].ToString());
_assetCompanyDetailslist = assetrep.GetAssetsForLocation(LocationID);
var model = _assetCompanyDetailslist;
return View(model);
}
else
{
return View();
}
}
}
in my .cshtml kendo grid i used this to read
.Read(read => read.Action("Index", "AssetByLocation").Data("getMsgType"))
This is my event in dropdownlist
.Events(events => events.Change("OnMsgTypeChange"))
There are my functions
var ddlItem;
function getMsgType() {
return {
LocationId: ddlItem
}
}
function OnMsgTypeChange(e) {
ddlItem = this.value();
$("#Grid").data("kendoGrid").dataSource.read();
}

I Finally got with this,
public ActionResult Index([DataSourceRequest]DataSourceRequest request, string LocationId)
{
if (Request.Params["LocationId"] != null)
{
using (var client = new HttpClient())
{
AssetRepository assetrep = new AssetRepository();
Guid LocationID = new Guid();
LocationID = new Guid(Request.Params["LocationId"].ToString());
var msgs = assetrep.GetAssetsForLocation(LocationID).ToDataSourceResult(request);
return Json(msgs);
}
}
else
{
return View();
}
}

Related

Asp.net Core Object reference not set to an instance of an object

ASP.NET CORE API
The logged in user gives an error in the code below while adding a photo. Can anybody help?
var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)
This code gives an error. Help me
Object reference not set to an instance of an object
PhotosController.cs
[HttpPost]
public ActionResult AddPhotoForCity(int cityId,[FromForm]PhotoForCreationDto photoForCreationDto)
{
var city = _appRepository.GetCityById(cityId);
if (city == null)
{
return BadRequest("Could not find the city.");
}
var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
karşılaştırmak gibi
if (currentUserId != city.UserId)
{
return Unauthorized();
}
var file = photoForCreationDto.File;
var uploadResult = new ImageUploadResult();
if (file.Length > 0)
{
using (var steam = file.OpenReadStream())
{
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(file.Name,steam)
};
uploadResult = _cloudinary.Upload(uploadParams);
}
}
photoForCreationDto.Url = uploadResult.Url.ToString();
photoForCreationDto.PublicId = uploadResult.PublicId;
var photo = _mapper.Map<Photo>(photoForCreationDto);
photo.City = city;
if (!city.Photos.Any(p => p.IsMain))
{
photo.IsMain = true;
}
city.Photos.Add(photo);
if (_appRepository.SaveAll())
{
//eklenen fotoğrafı döndürüyoruz
var photoToRetun = _mapper.Map<Photo>(photoForCreationDto);
return CreatedAtRoute("GetPhoto", new {id = photo.Id}, photoToRetun);
}
return BadRequest("Cloud not add the photo");
}
AuthController.cs
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
private IAuthRepository _authRepository;
private IConfiguration _configuration;
public AuthController(IAuthRepository authRepository, IConfiguration configuration)
{
_authRepository = authRepository;
_configuration = configuration;
}
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] UserForRegisterDto userForRegisterDto)
{
if (await _authRepository.UserExists(userForRegisterDto.UserName))
{
ModelState.AddModelError("UserName", "Username already exists");
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var userToCreate = new User
{
UserName = userForRegisterDto.UserName
};
var createdUser = await _authRepository.Register(userToCreate, userForRegisterDto.Password);
return StatusCode(201);
}
[HttpPost("login")]
public async Task<ActionResult> Login([FromBody] UserForLoginDto userForLoginDto)
{
var user = await _authRepository.Login(userForLoginDto.UserName, userForLoginDto.Password);
if (user == null)
{
return Unauthorized();
}
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_configuration.GetSection("AppSettings:Token").Value);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.UserName)
}),
Expires = DateTime.Now.AddDays(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key)
, SecurityAlgorithms.HmacSha512Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return Ok(tokenString);
}
}
From the above code snippet you have shared, they mostly likely reason you are getting this error is because the user is not logged in, and hence this line of code
User.FindFirst(ClaimTypes.NameIdentifier).Value
is throwing an exception.
You could either do it like this.
User.FindFirst(ClaimTypes.NameIdentifier)?.Value
Or
[HttpPost]
[Authorize] // make sure you authorize your action method by adding this attribute and
// only allow logged in user to access it.
public ActionResult AddPhotoForCity(int cityId,[FromForm]PhotoForCreationDto photoForCreationDto)
{
}
try this one:
var currentUserId = int.Parse(User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value);

MVC Core DropDownList selected value ignored

I am trying to access my page at: https://localhost:44319/Analyze/Index/6
The problem is that my drop down list always selects the first item in the list instead of the one provided by ID. While stepping through the debugger, before the View() is returned, I see that the SelectList was populated correctly.
AnalyzeController.cs
public IActionResult Index(int? Id)
{
return Index(Id ?? getStatementEndingById(Id).StatementEndingId);
}
[HttpPost]
public IActionResult Index(int StatementEndingId)
{
var statementEnding = getStatementEndingById(StatementEndingId);
ViewBag.StatementEndingId = new SelectList(
_context.StatementEnding.OrderByDescending(s => s.StatementEndingId),
"StatementEndingId",
"Name",
statementEnding);
return View(getPayments(statementEnding));
}
private StatementEnding getStatementEndingById(int? statementEndingId)
{
StatementEnding statementEnding;
if (statementEndingId.HasValue)
{
statementEnding = _context.StatementEnding.FirstOrDefault(s => s.StatementEndingId == statementEndingId);
}
else
{
statementEnding = _context.StatementEnding.OrderByDescending(s => s.StatementEndingId).FirstOrDefault();
}
return statementEnding;
}
Setting DropDownList in Razor
#Html.DropDownList("StatementEndingId", null, new { #class = "form-control mb-2 mr-sm-2" })
I am using ASP.NET Core 2.1.
Any suggestions are much appreciated. Thanks in advance.
First i would recomend to create a typed model, something like this one :
public class StatementViewModel
{
public int StatementEndingId { get; set; }
public List<SelectListItem> StatementEndings { get; set; }
}
Second fill the Model with all dropdown options (StatementEndings) and the selected one (StatementEndingId)
public IActionResult Index()
{
var model = new StatementViewModel();
model.StatementEndingId = getStatementEndingById(Id).StatementEndingId;
model.StatementEndings = _context.StatementEnding.OrderByDescending(s => s.StatementEndingId).Select(p => new SelectListItem() { Text = p.Name, Value = p.StatementEndingId }).ToList();
return View(model);
}
And for the last, in the view
#model StatementViewModel
#Html.DropDownListFor(m => m.StatementEndingId, Model.StatementEndings, null, new { #class = "form-control mb-2 mr-sm-2" })

ASP.Net core WebAPI controller- 200 status code but no response

I have following controller in my web API:
[Route("api/[controller]")]
public class User_TaskController : Controller
{
private readonly IUser_TaskRepository _taskRepository;
private readonly UserManager<ApplicationUser> _userManager;
private readonly WebAPIDataContext _context;
//Controller
public User_TaskController(IUser_TaskRepository taskRepository, UserManager<ApplicationUser> userManager, WebAPIDataContext context)
{
_taskRepository = taskRepository;
_userManager = userManager;
_context = context;
}
//Get methods
[HttpGet]
public IEnumerable<User_Task> GetAll()
{
return _taskRepository.GetAll();
}
[Authorize]
[HttpGet("current")]
public IActionResult GetCurrentUserTasks()
{
// Obtain stakeholderId
var stakeholderId = this.GetStakeholderId();
var userTasks = _taskRepository.GetUserTasks(stakeholderId);
return new ObjectResult(userTasks);
}
[HttpGet("{id}", Name = "GetTask")]
public IActionResult GetById(long id)
{
var item = _taskRepository.Find(id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
//Create
[Authorize]
[HttpPost]
public IActionResult Create([FromBody] User_Task item)
{
if (item == null)
{
return BadRequest();
}
var stakeholderId = this.GetStakeholderId();
_taskRepository.Add(item, stakeholderId);
var itemToReturn = _taskRepository.Find(item.TaskId);
if (item == null)
{
return NotFound();
}
return new ObjectResult(itemToReturn);
}
private long GetStakeholderId()
{
string currentUserId = _userManager.GetUserId(User);
long stakeholderId = 0;
var users = _userManager.Users;
foreach (var user in users)
{
if (user.Email == currentUserId)
{
var idForStakeholder = user.Id;
var stakeholders = _context.Stakeholders;
foreach (var stakeholder in stakeholders)
{
if (stakeholder.IdentityId == idForStakeholder)
{
stakeholderId = stakeholder.StakeholderId;
return stakeholderId;
}
}
}
}
return stakeholderId;
}
}
And corresponding repository:
public class User_TaskRepository : IUser_TaskRepository
{
private readonly WebAPIDataContext _context;
public User_TaskRepository(WebAPIDataContext context)
{
_context = context;
}
public IEnumerable<User_Task> GetAll()
{
return _context.User_Tasks.Include(task => task.Steps).ToList();
}
// Method that returns all the tasks of a specific user i.e. logged in used making the request
public ICollection<User_Task> GetUserTasks(long stakeholderId)
{
var userTasks = _context.User_Tasks
.Where(task => task.StakeholderId == stakeholderId).ToList();
return userTasks;
}
public void Add(User_Task item , long stakeholderId)
{
item.StakeholderId = stakeholderId;
_context.User_Tasks.Add(item);
_context.SaveChanges();
}
public User_Task Find(long key)
{
return _context.User_Tasks.Include(task => task.Steps).FirstOrDefault(t => t.TaskId == key);
}
}
public interface IUser_TaskRepository
{
void Add(User_Task item, long stakeholderId);
IEnumerable<User_Task> GetAll();
ICollection<User_Task> GetUserTasks(long stakeholderId);
User_Task Find(long key);
}
Problems:
For create method the record is added to the database but I do not get any response in Postman.
For getting tasks for a specific users i.e. GetCurrentUserTasks() untill last line before return statement, I see the tasks fetched however it returns nothing and I still get status 200 Ok on my angular2 frontend. I tried removing [Authorize] header but no effect.
Why is it happening?
For your Create() method, it seems like you're checking if the "item" variable is null, then returning the "itemToReturn" variable, which is probably null (which is why you get an empty result):
//Create
[Authorize]
[HttpPost]
public IActionResult Create([FromBody] User_Task item)
{
if (item == null)
{
return BadRequest();
}
var stakeholderId = this.GetStakeholderId();
_taskRepository.Add(item, stakeholderId);
var itemToReturn = _taskRepository.Find(item.TaskId);
if (item == null) // checking item instead of itemToReturn
{
return NotFound();
}
return new ObjectResult(itemToReturn);
}
Shouldn't you be checking if "itemToReturn" is null?
Since you are using ObjectResult(){} I believe the inline changes are what you are looking for.
[Authorize]
[HttpGet("current")]
public IActionResult GetCurrentUserTasks()
{
var status = HttpStatus.Ok; //<< add
// Obtain stakeholderId
var stakeholderId = this.GetStakeholderId();
var userTasks = _taskRepository.GetUserTasks(stakeholderId);
if(userTasks == null)
status = HttpStatusCode.NoContent;
return new ObjectResult(userTasks){StatusCode = (int)status };
}
Below your method with changes included
//Create
[Authorize]
[HttpPost]
public IActionResult Create([FromBody] User_Task item)
{
var status = HttpStatusCode.Ok;
if (item == null)
{
status = HttpStatusCode.BadRequest;
return BadRequest();
}
var stakeholderId = this.GetStakeholderId();
_taskRepository.Add(item, stakeholderId);
var itemToReturn = _taskRepository.Find(item.TaskId);
if (itemToReturn == null)
{
status = HttpStatusCode.NoContent;
return NotFound();
}
return new ObjectResult(itemToReturn){StatusCode = (int)status};
}
Now for GetCurrentUserTasks() method doesn't do what you are expecting equating _userManager.GetUserId(User); returns the USER's Id which is a GUID not an email therefore you logic in the for loop (why you are looping thru users, is a unusual step, useless really) kills the next loop structure. This is all based on the assumption on my part that you are using a unaltered Identity setup for ASp.net Core.
private long GetStakeholderId()
{
string currentUserId = _userManager.GetUserId(User); // << GUID
long stakeholderId = 0;
var users = _userManager.Users; //<< pointless
foreach (var user in users) // ^^^
{
if (user.Email == currentUserId) << // will never be TRUE
{
var idForStakeholder = user.Id;
var stakeholders = _context.Stakeholders;
foreach (var stakeholder in stakeholders)
{
if (stakeholder.IdentityId == idForStakeholder)
{
stakeholderId = stakeholder.StakeholderId;
return stakeholderId;
}
}
}
}
return stakeholderId; // WILL ALWAYS be 0
}
I am pretty sure at this point from the code posted you will get a OK 200 from the GetCurrentUserTasks() because it does run but never pulls the tasks for the user since the user is never actually found correctly in the base of your code.

asp.net mvc 4. 0 - multiple action to render data to same view

How i can overload actions in a controller.
public ActionResult OnlineHome()
{
OnlineDataModel dm = new OnlineDataModel();
dm.CatagoryData = new List<category>();
dm.ProductData = new List<product>();
dm.CatagoryData = db.categories.ToList();
return View(dm);
}
[HttpPost]
public ActionResult OnlineHome(int CategoryId)
{
OnlineDataModel dm = new OnlineDataModel();
dm.CatagoryData = new List<category>();
dm.ProductData = new List<product>();
dm.CatagoryData = db.categories.ToList();
Convert.ToInt32(CategoryId) select p).ToList() ;
var data= db.products.Where(d => d.CategoryID == CategoryId).ToList();
dm.ProductData = data.ToList();
ViewBag.data = data;
return View(dm);
}
[HttpPost]
public ActionResult OnlineHome(OnlineDataModel data)
{
return View();
}
please help. how i can overload the actions which will render data to same view
You can use the ActionName attribute if you want your code to do overloading.
[ActionName("MyOverloadedName")]
To Render the Same View, You can pass the Model and ViewName like this.
return View("ViewName",model);
you can provide ActionName attribute with different name while calling it from View. Like
[ActionName("OnlineHomeWithCategoryId")]
public ActionResult OnlineHome(int CategoryId)
{
}
[ActionName("OnlineHomeWithData")]
public ActionResult OnlineHome(OnlineDataModel data)
{
}
Now you just need to use these action names while calling these action metho

Data not binding to listbox in mvc4

I have listbox
#Html.ListBox("lais", new SelectList(Model.lista, "Value", "Text"), new {#class = "mylistbox"});
Here am getting list data but not binding to listbox (list items value )
This is my action method
public ActionResult PrintRFIDTag()
{
Print p =new Print();
p.lista = GetList();
return View(p);
}
public SelectList GetList()
{
System.Management.ManagementScope objMS =
new System.Management.ManagementScope(ManagementPath.DefaultPath);
objMS.Connect();
List<SelectListItem> items = new List<SelectListItem>();
SelectQuery objQuery = new SelectQuery("SELECT * FROM Win32_Printer");
ManagementObjectSearcher objMOS = new ManagementObjectSearcher(objMS, objQuery);
System.Management.ManagementObjectCollection objMOC = objMOS.Get();
foreach (ManagementObject Printers in objMOC)
{
if (Convert.ToBoolean(Printers["Network"])) // ALL NETWORK PRINTERS.
{
var emptyItem = new SelectListItem()
{
Value = Printers["Name"].ToString(),
Text = "00"
};
items.Add(emptyItem);
}
}
SelectList objselectlist = new SelectList(items,"Value");
return objselectlist;
}
}
Here is my model class
public class Print
{
public SelectList lista { get; set; }
public string Name { get; set; }
}
Returning from view but not binding to listbox
Your help will be appropriated
try this:
#Html.ListBoxFor(m=>m.lista ,Model.lista) and change line SelectList objselectlist = new SelectList(items,"Value"); to this: SelectList objselectlist = new SelectList(items,"Value","Text");