I'm using MVC3.
I have a ActionLink in my home page, which will redirect to another dueItem page:
#Html.ActionLink("Due Items", "Reports", "Reports", null, new { #class = "btn btn-sm btn-outline-secondary", #style = "color:black; font-size: 15px;" })
The controller & model of dueItem page are below:
Model:
public class ViewModel
{
public IEnumerable<InvHardwareModel>Report_HardwareListByExpiration { get; set; }
}
Controller:
public class ReportsController : Controller
{
// GET: Report
public ActionResult Reports()
{
if (Session["UserID"] == null || !(bool)Session["IsLoggedIn"])
{
return RedirectToAction("Login", "Account");
}
ViewModel myViewModel = new ViewModel
{
User = GetSessionInfoFromSessions(),
Params = new ParametersModel
{
Start_Date = new DateTime(2015, 12, 31),
End_Date = DateTime.Now.AddDays(60)
}
};
myViewModel.Report_HardwareListByExpiration = InvHardwareModel.Report_HardwareListByExpiration(myViewModel);
return View(myViewModel);
}
Now I want to remove this ActionLink and copy the code to my home page directly, but after I run the project it has a error:
Error page
My home page are using different controller:
public class HomeController : Controller
{
public ActionResult Index()
{
if (Session["UserID"] == null || !(bool)Session["IsLoggedIn"])
{
return RedirectToAction("Login", "Account");
}
var myViewAgModel = new ViewModel();
//Populate ViewModel that goes into Dashboards and Reports.
myViewAgModel.User = GetSessionInfoFromSessions();
var InvHardwareModel =new InvHardwareModel();
ViewBag.InvHardwareTotalPrice = InvHardwareModel.InvHardwareBalance(GetSessionInfoFromSessions(), true);
ViewBag.InvHardwareTotal = InvHardwareModel.InvHardwareCount(GetSessionInfoFromSessions(), true);
//myViewAgModel.Report_HardwareListByExpiration = InvHardwareModel.Report_HardwareListByExpiration(myViewAgModel);
return View(myViewAgModel);
}
Thanks!
Related
I'm starter in .NET MVC. I want to pass a model from one controller to another controller, model contain a password. My first controller is auth method, in that I used Claims, but another controller is a vote method there I need to Post an ID, Password and Vote. Password I need in vote controller for voting confirmation in database.
My code:
My model:
public class LoginModel
{
public string IDNP { get; set; }
public string VnPassword { get; set;
}
My first controller:
public class AuthController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(LoginModel model)
{
var data = new LoginData();
data.IDNP = model.IDNP;
data.VnPassword = model.VnPassword;
var response = await session.Login(data);
if (response.Status == true)
{
var authclaims = new List<Claim>()
{
new Claim(ClaimTypes.Name, data.IDNP),
};
var authIdentity = new ClaimsIdentity(authclaims, "User Identity");
var userPrincipal = new ClaimsPrincipal(new[] {authIdentity});
HttpContext.SignInAsync(userPrincipal);
return RedirectToAction("Index", "Vote",new{pass=data.VnPassword});
}
else
{
return View();
}
}
}
My second controller:
public class VoteController : Controller
{
private IVote connection;
public VoteController()
{
var bl = new BusinessManager();
connection = bl.GetVote();
}
[Authorize]
public IActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(VoteModel vote)
{
var identity = (ClaimsIdentity)User.Identity;
var voteindex = new VoteData();
voteindex.IDNP = identity.Name;
voteindex.VnPassword = ;
voteindex.Party = vote.Party;
var response = await connection.Vote(voteindex);
if (response.Status == true)
return RedirectToAction("Index", "Home");
else
{
return RedirectToAction("Index", "Auth");
}
}
}
Actually, it's a bad idea to send Id and Password to another controller. It conflicts SRP rule.
You should have only one controller that gets and uses password.
However, if you want to use this action, you can use this
Currently i am using variables inside my view that have been declared within a model, and assigned values within the respective controller. I am using Model.variableName to reference these variables, however the following exception is thrown during debugging;
I am using the following namespaces within my view;
#using ProjectName.Models
#model Category
My class model;
public class Category
{
public string result { get; set; }
}
My controller;
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult ReadCategory()
{
var dataFile = Server.MapPath("~/App_Data/Category.txt");
Category passCategory = new Category
{
result = "",
delimiterChar = new[] { ',' },
userData = System.IO.File.ReadAllLines(dataFile)
};
return View(passCategory);
}
Any help would be greatly appreciated!
Try moving your code to your index action result like this: (as I suspect your action result ReadCategory is not being utilized)
public ActionResult Index()
{
var dataFile = Server.MapPath("~/App_Data/Category.txt");
Category passCategory = new Category
{
result = "",
delimiterChar = new[] { ',' },
userData = System.IO.File.ReadAllLines(dataFile)
};
return View(passCategory);
}
I'm using Telerik Scheduler asp.net MVC Core UI Controller. I have a problem with the following methods Date_Grouping_Read, Date_Grouping_Destroy, Date_Grouping_Create and Date_Grouping_Update. They are not firing when I try to update or create meeting?
//HomeController
namespace TelerikScheduler.Controllers
{
public partial class HomeController : Controller
{
private IMeetingData meetingData;
public HomeController(IMeetingData meetingData)
{
this.meetingData = meetingData;
}
public IActionResult Index()
{
var model = new HomePageViewModel();
model.Rooms = meetingData.GetAll();
return View(model);
}
public IActionResult Details(int id)
{
var model = meetingData.Get(id);
if (model == null)
{
return RedirectToAction("Index");
}
return View(model);
}
public IActionResult Error()
{
return View();
}
public virtual JsonResult Date_Grouping_Read([DataSourceRequest] DataSourceRequest request)
{
return Json(meetingData.GetAll().ToDataSourceResult(request));
}
public virtual JsonResult Date_Grouping_Destroy([DataSourceRequest] DataSourceRequest request, Meeting meeting)
{
meetingData.delete(meeting);
return Json(new[] { meeting }.ToDataSourceResult(request, ModelState));
}
public virtual JsonResult Date_Grouping_Create([DataSourceRequest] DataSourceRequest request, Meeting meeting)
{
meetingData.Insert(meeting);
return Json(new[] { meeting }.ToDataSourceResult(request, ModelState));
}
public virtual JsonResult Date_Grouping_Update([DataSourceRequest] DataSourceRequest request, Meeting meeting)
{
meetingData.Update(meeting);
return Json(new[] { meeting }.ToDataSourceResult(request, ModelState));
}
}
}
View
#(Html.Kendo().Scheduler<Meeting>().Name("Meeting").Date(new DateTime(2017, 5, 13))
.StartTime(new DateTime(2017, 5,13, 7, 00, 00))
.Views(views=>{
views.DayView();
views.AgendaView();
})
.Height(600)
.Timezone("Etc/UTC")
.Group(group => { group.Resources("Rooms"); group.Date(true); })
.Resources(resource =>
{
resource.Add(m => m.RoomId).Title("Room").Name("Rooms").DataTextField("Text").DataValueField("Value").DataColorField("Color").BindTo(new[] {
new { Text = "Meeting Room 101", Value = 1, Color = "#6eb3fa" },
new { Text = "Meeting Room 201", Value = 2, Color = "#f58a8a" }
});
resource.Add(m => m.Attendees)
.Title("Attendees")
.Multiple(true)
.DataTextField("Text")
.DataValueField("Value")
.DataColorField("Color")
.BindTo(new[] {
new { Text = "Alex", Value = 1, Color = "#f8a398" } ,
new { Text = "Bob", Value = 2, Color = "#51a0ed" } ,
new { Text = "Charlie", Value = 3, Color = "#56ca85" }
});
}).DataSource(d => d
.Model(m =>
{
m.Id(f => f.RecordId);
m.Field(f => f.Title).DefaultValue("No title");
m.Field(f => f.Title).DefaultValue("No title");
})
.Read("Date_Grouping_Read", "Scheduler")
.Create("Date_Grouping_Create", "Scheduler")
.Destroy("Date_Grouping_Destroy", "Scheduler")
.Update("Date_Grouping_Update", "Scheduler")
)
.BindTo(Model.Rooms).Deferred())
#section scripts {
#Html.Kendo().DeferredScripts();
}
Of course they won't fire when the control is setup for the wrong Controller...
.Read("Date_Grouping_Read", "Scheduler")
.Create("Date_Grouping_Create", "Scheduler")
.Destroy("Date_Grouping_Destroy", "Scheduler")
.Update("Date_Grouping_Update", "Scheduler")
All show Scheduler when since you have posted code for Home should be
.Read("Date_Grouping_Read", "Home")
.Create("Date_Grouping_Create", "Home")
.Destroy("Date_Grouping_Destroy", "Home")
.Update("Date_Grouping_Update", "Home")
I have strongly typed view model and in one of class object I am passing list of options that I need to present in #html.Dropdownlist
View Model
public class CreateCampaign_VM
{
public MarketingCampaign MarketingCampaign { get; set; }
public List<MarketingCampaignType> MarketingCampaignType { get; set; }
}
Controller method
private CreateCampaign_VM GetCampaignObject()
{
CreateCampaign_VM _CampaignObject = new CreateCampaign_VM();
_CampaignObject.MarketingCampaignType.Add(new MarketingCampaignType {
CampaignTypeID = 1,
CampaignTypeTitle = "Email",
Description = "Email"
});
_CampaignObject.MarketingCampaignType.Add(new MarketingCampaignType
{
CampaignTypeID = 2,
CampaignTypeTitle = "Text",
Description = "Text"
});
_CampaignObject.MarketingCampaignType.Add(new MarketingCampaignType
{
CampaignTypeID = 3,
CampaignTypeTitle = "Post",
Description = "Post"
});
return _CampaignObject;
}
...
public ActionResult CreateCampaign_Title()
{
return PartialView("CreateCampaign_Title_Partial", GetCampaignObject());
}
Razor view
#model App.Business.Entities.CreateCampaign_VM
#using (Html.BeginForm("CreateCampaign_Title", "Campaign", FormMethod.Post, new { id = "CreateCampaignTitleForm" }))
{
.....
#Html.DropDownListFor(// 'MarketingCampaignType object' need help here
//...
}
Try this:
#Html.DropDownListFor(m => m.MarketingCampaign , new SelectList(Model.MarketingCampaignType, "CampaignTypeTitle", "CampaignTypeId"), new { id = "yourElementIdIfAny", #class = "yourClassNameIfAny" })
HI I am stuck in getting data that i need to display in kendo UI GRID , Initially I am able to see the button and textbox and grid as well but when i enter the value in textbox and then press the button i need to show that entered values in kendo UI GRID ...
When I run this application in google chrome it was giving empty grid,after enters the value and then press the submit button but when I run this one in IE8 it was giving error like this at starting stage itself....
Unhandled exception at line 238, column 37 in Function code
0x800a138f - Microsoft JScript runtime error: 'data.EmployeeDetails.EmployeeId' is null or not an object
and this is my model
public class TextBoxGrid
{
public string EnteredValue { get; set; }
public List<EmployeeDetails> employees;
}
public class ParentViewModel
{
public EmployeeDetails EmployeeDetails { get; set; }
public TextBoxGrid TextBoxGrid { get; set; }
}
public class EmployeeDetails
{
public string EmployeeId { get; set; }
public string ManagerId { get; set; }
}
this is my controller
public class EnterValuesGridController : Controller
{
private static List<EmployeeDetails> empdtls;
public ActionResult Index( ParentViewModel model)
{
var viewmodel = new ParentViewModel
{
TextBoxGrid = new TextBoxGrid { employees = GetEmployee().ToList() }
};
return View(viewmodel);
}
[HttpPost]
public ActionResult PostValues(TextBoxGrid model)
{
TempData["enteringValue"] = model.EnteredValue;
var viewmodel = new ParentViewModel
{
TextBoxGrid = new TextBoxGrid { employees = GetEmployee().ToList() }
};
//ParentViewModel p = new ParentViewModel();
//TextBoxGrid t = new TextBoxGrid();
//t.EnteredValue = "a";
//TempData["a1"] = t.EnteredValue;
//t.employees = GetEmployee().ToList();
//p.TextBoxGrid = t;
//return View("Index", p);
return View("Index", viewmodel);
}
public IEnumerable<EmployeeDetails> GetEmployee()
{
string enteredValueId =(string) TempData["enteringValue"];
string managerId = "M" +enteredValueId;
empdtls = new List<EmployeeDetails>();
EmployeeDetails em1 = new EmployeeDetails();
em1.EmployeeId = enteredValueId;
em1.ManagerId = managerId;
empdtls.Add(em1);
return empdtls.AsEnumerable();
}
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request)
{
return Json(GetOrders().ToDataSourceResult(request));
}
private IEnumerable<EmployeeDetails> GetOrders()
{
return GetEmployee().AsEnumerable();
}
}
and this is my view
#model KendoPratapSampleMVCApp.Models.ParentViewModel
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm("PostValues", "EnterValuesGrid", FormMethod.Post))
{
#Html.TextBoxFor(m=>m.TextBoxGrid.EnteredValue)
<input type="submit" name="Submitbutton1" value="Submit1" />
#(Html.Kendo().Grid<KendoPratapSampleMVCApp.Models.ParentViewModel>()
.Name("grid")
.Columns(columns => {
columns.Bound(s=>s.EmployeeDetails.EmployeeId).Filterable(false).Width(100);
columns.Bound(s => s.EmployeeDetails.ManagerId).Filterable(false).Width(100);
})
.Filterable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("Orders_Read", "EnterValuesGrid"))
)
)
}
I am not sure where I am doing wrong, Would you pls suggest any ideas on this one ..
Many thanks...., Do i need to do any changes in UI GRID I have tried changing the post values method ...but it didnot worked for me ...
UPDATE :
changed tempData to view Bag...
[HttpPost]
public ActionResult PostValues(ParentViewModel model)
{
ViewBag.item = model.TextBoxGrid.EnteredValue;
var viewmodel = new ParentViewModel
{
TextBoxGrid = new TextBoxGrid { employees = GetEmployee().ToList() }
};
//ParentViewModel p = new ParentViewModel();
//TextBoxGrid t = new TextBoxGrid();
//t.EnteredValue = "a";
//TempData["a1"] = t.EnteredValue;
//t.employees = GetEmployee().ToList();
//p.TextBoxGrid = t;
//return View("Index", p);
return View("Index", viewmodel);
}
public IEnumerable<EmployeeDetails> GetEmployee()
{
string enteredValueId = (string)ViewBag.item;
string managerId = "M" +enteredValueId;
empdtls = new List<EmployeeDetails>();
EmployeeDetails em1 = new EmployeeDetails();
em1.EmployeeId = enteredValueId;
em1.ManagerId = managerId;
empdtls.Add(em1);
return empdtls;
}
Hi pratap i just update your code,
Model
public class TextBoxGrid
{
public string EnteredValue { get; set; }
public List<EmployeeDetails> employees;
}
public class ParentViewModel
{
public EmployeeDetails EmployeeDetails { get; set; }
public TextBoxGrid TextBoxGrid { get; set; }
}
public class EmployeeDetails
{
public string EnteredValue { get; set; }
public string EmployeeId { get; set; }
public string ManagerId { get; set; }
}
View
#model TwoModelInSinglePageModel.EmployeeDetails
#{
ViewBag.Title = "Index";
}
<script src="~/Script/Jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="~/Script/jquery-ui-1.8.20.min.js" type="text/javascript"></script>
<script src="#Url.Content("~/Script/kendo.all.min.js")" type="text/javascript"></script>
<script src="~/Script/kendo.web.min.js" type="text/javascript"></script>
<script src="~/Script/kendo.aspnetmvc.min.js" type="text/javascript"></script>
#using (Html.BeginForm("PostValues", "Test", FormMethod.Post))
{
#Html.TextBoxFor(m => m.EnteredValue)
<input type="submit" name="Submitbutton1" value="Submit1" />
#(Html.Kendo().Grid<TwoModelInSinglePageModel.EmployeeDetails>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(s => s.EmployeeId);
columns.Bound(s => s.ManagerId);
})
.Filterable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("Orders_Read", "Test"))
)
)
}
Controller
private static List<EmployeeDetails> empdtls;
public ActionResult PostValues()
{
return View();
}
[HttpPost]
public ActionResult PostValues(EmployeeDetails model)
{
ViewBag.item = model.EnteredValue;
ParentViewModel viewmodels = new ParentViewModel
{
TextBoxGrid = new TextBoxGrid { employees = GetEmployee().ToList() }
};
ParentViewModel viewmodel = new ParentViewModel();
EmployeeDetails em1 = new EmployeeDetails();
for (int i = 0; i < viewmodels.TextBoxGrid.employees.Count(); i++)
{
em1.EmployeeId = viewmodels.TextBoxGrid.employees[i].EmployeeId;
em1.ManagerId = viewmodels.TextBoxGrid.employees[i].ManagerId;
viewmodel.EmployeeDetails = em1;
}
Session["EM1"] = em1;
return View("PostValues", em1);
}
public List<EmployeeDetails> GetEmployee()
{
string enteredValueId = (string)ViewBag.item;
string managerId = "M" + enteredValueId;
empdtls = new List<EmployeeDetails>();
EmployeeDetails em1 = new EmployeeDetails();
em1.EmployeeId = enteredValueId;
em1.ManagerId = managerId;
if (Session["EM1"] != null)
{
em1 = Session["EM1"] as EmployeeDetails;
empdtls.Add(em1);
Session["EM1"] = null;
}
else
{
empdtls.Add(em1);
}
return empdtls;
}
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request, EmployeeDetails model)
{
return Json(GetEmployee().ToDataSourceResult(request));
}
OK, I read through your post again and you want to submit the form when click on the button actually. So, let's try to put the value in the session
Session["enteringValue"] = model.EnteredValue;
And you can retrieve it using
string enteredValueId = (string)(Session["enteringValue"]);