Pass value in asp.net mvc - asp.net-mvc

I am trying to pass data of method to another method. Can you help me please?
Here is my code: return View(model); model should be pass public ActionResult ShowData(Student model) method.
public ActionResult ShowData(int? ID)
{
var model = new StudentModel
{
StudentData = stdDef
};
return View(model);
}
[HttpPost]
public ActionResult ShowData(Student model) {

This is how it is done. Please pay attention to my comments in the code:
Controller/Model:
public class StudentModel
{
public string StudentData { get; set; }
}
public class HomeController : Controller
{
public string PassDataToMe(StudentModel model)
{
return model.StudentData;//no view defined
}
public ActionResult ShowData(int? ID)
{
var stdDef = "stdDef";
var model = new StudentModel
{
StudentData = stdDef
};
return View(model);
}
[HttpPost]
//!changed this to studentmodel
public ActionResult ShowData(StudentModel model)
{
//this is how you pass limited bytes of data that are not encrypted
return RedirectToAction("PassDataToMe", model);
}
View:
#model Testy20161006.Controllers.StudentModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ShowData</title>
</head>
<body>
<div>
#using (Html.BeginForm())
{
#Html.LabelFor(r => r.StudentData);
#Html.TextBoxFor(r=>r.StudentData);
<input type="submit" value="submit" />
}
</div>
</body>
</html>

Related

how to send all users list to a view in asp.net core 3 from controller

how to send all users list to a view in asp.net core 3 mvc from controller
public IActionResult Users()
{
var alluser = _db.Users.ToList();
return View(alluser);
}
create a class ApplicationDbUser as an example and inherit from IdentityUser to inherit all the properites from the AspNetUsers as follow :
public class ApplicationDbUser : IdentityUser
{
}
then you should use a context as a db (_db in your question) to get the data from the database using EntityFramework as the following code :
public class ApplicationDbContext : IdentityDbContext<ApplicationDbUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
now in your controller you can use the code as the following :
private readonly RoleManager<IdentityRole> _roleManager;
private readonly UserManager<ApplicationDbUser> _userManager;
public ExampleController(UserManager<ApplicationDbUser> userManager, RoleManager<IdentityRole> roleManager)
{
_userManager = userManager;
_roleManager = roleManager;
}
public IActionResult Index()
{
var allUsers = _userManager.Users.ToList();
return View(allUsers);
}
You can use it by using #model in the Index view page
in the Index.cshtml you can do the following :
#model IEnumerable<ApplicationDbUser>
<!DOCTYPE html>
<html>
<head>
<title>my page example</title>
</head>
<body>
<div>
<table>
#foreach (var item in Model)
{
<tr>
<td>
#item.Email
</td>
</tr>
}
</table>
</div>
</body>
</html>

Model returning null from a View with multiple models

I have two models, LoginModel and DatabaseModel. Combining them, I have created DatabaseCombinedWithOtherModel. The View, Login.cshtml is Strongly-Typed with the combined model. On running the Login.cshtml, the LoginModel returns null
I have all the necessary get and set methods
Here is the Controller class
namespace ReadingCat.Controllers
{
public class LoginController : Controller
{
private int userid;
// GET: Login
[HttpGet]
public ActionResult Login()
{
return View(new DatabaseCombinedWithOtherModel());
}
[HttpPost]
public ActionResult Login(DatabaseCombinedWithOtherModel model)
{
string realPassword = "";
string paswordFromUser = "";
string query = "SELECT password, userid FROM USERS WHERE username
= '" + model.loginModel.username + "'";
DataSet dataSet = model.databaseModel.selectFunction(query);
if (realPassword == paswordFromUser)
{
userid =
Convert.ToInt32(dataSet.Tables[0].Rows[0].ItemArray[1]);
model.loginModel.userid = userid;
return View("~/Views/Profile/Profile.cshtml",
model.loginModel);
}
else
return View();
}
}
}
Here is the Model:
namespace ReadingCat.Models
{
public class DatabaseCombinedWithOtherModel
{
public DatabaseModel databaseModel { get; set; }
public LoginModel loginModel { get; set; }
}
}
And here is the View:
#model ReadingCat.Models.DatabaseCombinedWithOtherModel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Login</title>
<!-- Main css -->
<link rel="stylesheet" href="~/css/login.css">
</head>
<body>
<div class="login-page">
<div class="form">
<form class="register-form">
</form>
#using (Html.BeginForm("Login", "Login", FormMethod.Post))
{
<form class="login-form">
#Html.TextBox("Username", null, new { placeholder = "Username",
#class = "login.css" })
#Html.ValidationMessageFor(model => model.loginModel.username);
#Html.Password("Password", null, new { placeholder = "Password",
#class = "login.css" })
#Html.ValidationMessageFor(model => model.loginModel.password);
<div class="form-submit">
<button type="submit" value="Submit" class="submit"
id="submit" name="submit">Login</button>
</div>
<p class="message">Not registered? Create an account</p>
</form>
}
</div>
</div>
<img class="coffee-image" src="~/images/coffee.gif" alt="">
It is giving the following error
System.NullReferenceException: 'Object reference not set to an instance
of
an object.'
ReadingCat.Models.DatabaseCombinedWithOtherModel.loginModel.get returned
null.
I think this error about not fully declare DatabaseCombinedWithOtherModelthis model.
Please try this code.
private int userid
DatabaseCombinedWithOtherModel modelobj = new DatabaseCombinedWithOtherModel();
// GET: Login
[HttpGet]
public ActionResult Login()
{
return View(modelobj);
}
And also try this thing that before call the model in view firstly add some
values in objects from controller side pass return View(modelobj);and then call in view side.
Since you are not seting the loginmodel, it will be null Which will throw the exception.
Either initialize the loginModel in the otherModel's constructor or in the Login get action.
Try
namespace ReadingCat.Models
{
public class DatabaseCombinedWithOtherModel
{
public DatabaseModel databaseModel { get; set; }
public LoginModel loginModel { get; set; }
}
public DatabaseCombinedWithOtherModel()
{
loginModel = new LoginModel();
databaseModel = new DatabaseModel();
}
}
or
[HttpGet]
public ActionResult Login()
{
var vm = new DatabaseCombinedWithOtherModel()
vm.loginModel = new LoginModel();
vm.databaseModel = new DatabaseModel();
return View(vm);
}
The mentioned error goes away if #Html.Textbox is replaced with #Html.EditorFor. Then, another error arises with the DatabaseModel. It returns null. So I created a different object of DatabaseModel and worked with that.

How to use RadioButton to render View

I have a controller as shown below.
public ActionResult Index()
{
return View(db.FEE_TYPES.ToList());
}
By default it will render a View called Index. However, I have three views I want to Render
Index
Index2
Index3
I want to have three RadioButtons on the View
RadioButton1
RadioButton2
RadioButton3
When RadioButton1 is clicked, Render Index.
When RadioButton2 is clicked, Render Index2
When RadioButton3 is clicked, Render Index3
Please how do I achieve this?
I have Created a Demo from your Code Reference.
First i have create a Model with 3 properties in it.
Model
public class DemoModel
{
public string Radio1 { get; set; }
public string Radio2 { get; set; }
public string Radio3 { get; set; }
}
After creating a Model i have created a Controller with name RadioRenderController in that controller i have added 4 Action Method in that Index returns Main View.
And Remaining 3 Action Methods [ GetView1 , GetView2 , GetView3 ] return partial View.
Controller
using System.Web.Mvc;
using WebApplication6.Models;
namespace WebApplication6.Controllers
{
public class RadioRenderController : Controller
{
// GET: RadioRender
public ActionResult Index()
{
DemoModel DemoModel = new Models.DemoModel();
return View(DemoModel);
}
public ActionResult GetView1()
{
return PartialView("_DemoView1");
}
public ActionResult GetView2()
{
return PartialView("_DemoView2");
}
public ActionResult GetView3()
{
return PartialView("_DemoView3");
}
}
}
View
#model WebApplication6.Models.DemoModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function GetView1() {
$("#viewPlaceHolder").load("/RadioRender/GetView1");
}
function GetView2() {
$("#viewPlaceHolder").load("/RadioRender/GetView2");
}
function GetView3() {
$("#viewPlaceHolder").load("/RadioRender/GetView3");
}
</script>
</head>
<body>
<div>
#Html.RadioButtonFor(m => m.Radio1, "1", new { #onclick = "GetView1();" }) Radio1
</div>
<div>
#Html.RadioButtonFor(m => m.Radio1, "2", new { #onclick = "GetView2();" }) Radio2
</div>
<div>
#Html.RadioButtonFor(m => m.Radio1, "3", new { #onclick = "GetView3();" }) Radio3
</div>
<div id="viewPlaceHolder"></div>
</body>
</html>
Partial Views
Output

Post from MVC view don't get bind to controller model

I have a partial view which is displayed on modal window:
public ActionResult Details(string test)
{
var model = _taskService.GetDocumentTasks(test);
return PartialView("_Details", new CustomViewModel { TaskList = model.ToList() });
}
public class CustomViewModel
{
public DocumentStatus Status { get; set; }
public IList<DocumentTask> TaskList { get; set; }
}
I am able to loop TaskList in the view and draw form fields like this:
#model CustomViewModel
#using (Html.BeginForm())
{
#for (int i = 0; i < Model.TaskList.Count(); i++)
{
#Html.HiddenFor(m => m.TaskList[i].TaskId)
<div class="col-sm-6 col-md-4">
<img src="#Html.EditorFor(m => m.TaskList[i].DocumentPath)">
.. other form items here
</div>
}
<input class="btn btn-primary" type="submit" value="Save" />
}
This displays the form fields but when I click the submit button the modal which is sent to the controller is null. I have tried a few different ways of binding it but no success. The model on on the below controller is always null. Any idea how to bind the submitted form details to controller model?
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Details(CustomViewModel model)
{
}
Thanks.
This will work. I made some minor changes, so please follow this:
Controller/Model:
public class HomeController : Controller
{
public class TaskService
{
public Collection<DocumentTask> GetDocumentTasks(string test)
{
Collection<DocumentTask> aCollection = new Collection<DocumentTask>();
var documentTaska = new DocumentTask { TaskId = "patha", DocumentPath = "~/Images/w.JPG" };
var documentTaskb = new DocumentTask { TaskId = "pathb", DocumentPath = "~/Images/w.JPG" };
var documentTaskc = new DocumentTask { TaskId = "pathc", DocumentPath = "~/Images/w.JPG" };
var documentTaskd = new DocumentTask { TaskId = "pathd", DocumentPath = "~/Images/w.JPG" };
aCollection.Add(documentTaska);
aCollection.Add(documentTaskb);
aCollection.Add(documentTaskc);
aCollection.Add(documentTaskd);
return aCollection;
}
}
public class DocumentStatus { }
public class DocumentTask
{
public string TaskId { get; set; }
public string DocumentPath { get; set; }
public string UserDataToProveItWorking { get; set; }
}
public class CustomViewModel
{
public DocumentStatus Status { get; set; }
public IList<DocumentTask> TaskList { get; set; }
}
TaskService _taskService = new TaskService();
public ActionResult Overview()
{
return View();
}
public ActionResult Details(string test)
{
var model = _taskService.GetDocumentTasks(test);
return PartialView("_Details", new CustomViewModel { TaskList = model.ToList() });
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Details(CustomViewModel model)
{
return View("Overview");
}
View Overview.cshtml:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Overview</title>
</head>
<body>
<div>
#Html.ActionLink("GetPartialView", "Details", new { test = "aTestValue"})
</div>
</body>
</html>
Partial View _Detials.cshtml
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Overview</title>
</head>
<body>
<div>
#Html.ActionLink("GetPartialView", "Details", new { test = "aTestValue"})
</div>
</body>
</html>

Is it possible to pass a ViewModel object encapsulating Person to a Create view but only receive a Person object from a POST Create action method?

I have a domain model and a view model as follows:
Domain Model:
namespace MvcApplication1.Models
{
public enum Sex { Male, Female };
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
[Required(ErrorMessage="Please select either Female or Male.")]
public Sex? Sex { get; set; }
}
}
View Model:
namespace MvcApplication1.ViewModels
{
public class HomeCreateVM
{
public HomeCreateVM()
{
}
public HomeCreateVM(Person p)
{
Person = p;
SelectList = p.Sex.GetSelectList();
}
public Person Person { get; set; }
public SelectList SelectList { get; set; }
}
}
The auxiliary extension method is defined as follows:
namespace MvcApplication1.Models
{
public static class Utilities
{
public static SelectList GetSelectList<XXX>(this XXX? obj) where XXX : struct
{
var values = from XXX x in Enum.GetValues(typeof(XXX))
select new { Text = x.ToString(), Value = x };
return new SelectList(values, "Value", "Text", obj);
}
}
}
Controller:
public ActionResult Create()
{
var p = new Person();
return View(new HomeCreateVM(p));
}
[HttpPost]
public ActionResult Create(Person hc)// the source of problem!
{
if (ModelState.IsValid)//always false!
{
TempData["status"] = hc;
return RedirectToAction("Confirm");
}
else
return View(new HomeCreateVM(hc));
}
HomeCreateVM.cshtml:
#model MvcApplication1.ViewModels.HomeCreateVM
<div>
Name: #Html.EditorFor(model => model.Person.Name)</div>
<div>
Sex: #Html.DropDownListFor(model => model.Person.Sex, Model.SelectList, "--Select--")</div>
Create View:
#model MvcApplication1.ViewModels.HomeCreateVM
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>HomeCreateVM</legend>
#Html.EditorForModel()
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Question:
There is no problem if the POST Create action method accepts a HomeCreateVM object as the argument.
However, if I change the POST Create action method argument from HomeCreateVM to Person (as shown in the code above), ModelState.IsValid always returns false.
The question is: "Is it possible to pass a ViewModel object to a Create view but only accept a DomainModel object from a POST Create action method?"
Because your view is strongly typed to the view model your form fields will look like this:
<input type="text" name="Person.Name" />
and if you want to bind correctly you need to specify the prefix:
[HttpPost]
public ActionResult Create([Bind(Prefix = "Person")]Person hc)
{
...
}

Resources