POSTing data in ASP.NET MVC 4 - asp.net-mvc

I'm currently working on an ASP.NET MVC 4 app. I'm pretty new to ASP.NET MVC. Right now, I have a form coded up like this:
<form role="form" method="post" action="/contact/new">
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label for="name">Name</label>
<div id="name">
<input class="form-control" type="text" autocomplete="off" />
</div>
</div>
<div class="form-group">
<label for="gender">Gender</label>
<select id="gender" class="form-control">
<option value="m">Male</option>
<option value="f">Female</option>
</select>
</div>
<div class="form-group">
<label for="email">Email Address</label>
<input class="form-control" type="email" autocomplete="off" />
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
My controller and action look like the following:
public class ContactController : Controller
{
public ActionResult New()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult New()
{
return View();
}
}
My challenge is, I do not know what to put for the parameters of the HttpPost action in the controller. What should I put here?
Thanks!

MVC is based on Model View Controller. you should have a model for the View and your view should be strongly typed to its model.
If you don't want strongly typed view with some Model class, you have to read the form data from Request:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult New(FormCollection form)
{
string Name = form["UserName"].ToString();
return View();
}
and add name attribute to your input elements:
<input class="form-control" type="text" name="UserName" autocomplete="off" />
you should see these few links for making understanding of strongly type view and form post:
Dyanmic VS Strong Typed Views
What is strongly typed View in asp.net mvc
Why we need Strongly typed View

First, you need to ensure that the /name/ attributes on your form controls are filled out.
Then, you should define a ViewModel class called NewContactViewModel and your ActionResult as such:
public class NewContactViewModel
{
public string name { get; set; }
public string gender { get; set; }
public string email { get; set; }
}
[HttpPost]
public ActionResult New(NewContactViewModel model)
{
}

Related

Couldn't Add two numbers and get the Total using Asp.net MVC

I am trying to do a simple calculator program in asp.net MVC. I like to add two number and get the total. But I couldn't do the task. I am a beginner at asp.net MVC. code which I tried so far I attached below.
Model
namespace WebApplication30.Models
{
public class cal
{
public int no1 { get; set; }
public int no2 { get; set; }
public int tot { get; set; }
}
}
Controller
public class CalController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(cal c)
{
c.tot = c.no1 + c.no2;
return View(c);
}
}
** This is a View pass the values from the controller**
#model WebApplication30.Models.cal
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div class="row">
#using (Html.BeginForm("Index", "cal", FormMethod.Post))
{
<div class="form-group">
<label for="no">No 1</label>
<input type="text" class="form-control" id="no1" name="no1">
</div>
<div class="form-group">
<label for="pwd">No 2</label>
<input type="text" class="form-control" id="no2" name="no2">
</div>
<div class="form-group">
<label for="pwd">total</label>
<input type="text" class="form-control" id="tot" name="tot">
</div>
<button type="submit" class="btn btn-default">Submit</button>
}
</div>
enter image description here
You need to bind the input value to the cal Model. Also, need to add cal model when get index action called .
CONTROLLER
using System;
using System.Web.Mvc;
using System.Collections.Generic;
using WebApplication30.Models;
namespace WebApplication30
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View(new cal());
}
[HttpPost]
public ActionResult Index(cal c)
{
c.tot = c.no1 + c.no2;
return View(c);
}
}
}
VIEW
#model WebApplication30.Models.cal
#{
ViewBag.Title = "Index";
}
<body>
<h2>Index</h2>
<div class="row">
#using (Html.BeginForm("/Index", "Home", FormMethod.Post))
{
<div class="form-group">
<label for="no">No 1</label>
<input type="text" class="form-control" id="no1" name="no1" value="#Model.no1">
</div>
<div class="form-group">
<label for="pwd">No 2</label>
<input type="text" class="form-control" id="no2" name="no2" value="#Model.no2">
</div>
<div class="form-group">
<label for="pwd">total</label>
<input type="text" class="form-control" id="tot" name="tot" value="#Model.tot">
</div>
<button type="submit" class="btn btn-default">Submit</button>
}
</div>
</body>
NOTE: add / before Index while submitting the form it creates sometimes a problem.
DEMO

How to pass modified model back to Controller in ASP.NET Core

I have the following model:
public class Card
{
[DataType(DataType.Date)]
[BindProperty]
public DateTime Day { get; set; }
[BindProperty]
public string Field { get; set; }
}
The following Controller:
// GET: Card
public async Task<IActionResult> Index(DateTime? day)
{
return View(model);
}
public async Task<IActionResult> Refresh(DateTime? Day, string Field)
{
return RedirectToAction("Index", Day);
}
The following View:
#model Card
<h1>Cards</h1>
<div class="text-center">
<label asp-for="Day" class="control-label"></label>
<input asp-for="Day" class="form-control" />
</div>
<div class="text-center">
<label asp-for="Field" class="control-label"></label>
<select asp-for="Field" class="form-control" asp-items="ViewBag.Fields"></select>
</div>
<form asp-action="Refresh">
#Html.HiddenFor(x => x.Day)
#Html.HiddenFor(y => y.Field)
<input type="submit" value="Refresh" class="btn btn-default" />
</form>
No matter what I change, I always get the initial Day value back and null as the Field, like the Model has never been changed…
So how can I post back the modified model to my controller?
your form is submitting the values from the hidden fields which are rendered on the page when the view first loads and then they are never modified (which is why you are seeing the default initialization for Day and for Field). Your editable fields are outside of the form and are what you're editing but they never get submitted to the server. I think the main takeaway here for you is that forms only know about inputs that exist inside of them (unless you write some javascript magic to handle this but there is no reason to do so in this case)
You need to remove the hidden fields and put your editable fields inside the form as follows:
#model Card
<h1>Cards</h1>
<form method="post" asp-action="Refresh">
<div class="text-center">
<label asp-for="Day" class="control-label"></label>
<input asp-for="Day" class="form-control" />
</div>
<div class="text-center">
<label asp-for="Field" class="control-label"></label>
<select asp-for="Field" class="form-control" asp-items="ViewBag.Fields"></select>
</div>
<input type="submit" value="Refresh" class="btn btn-default" />
</form>
you can also change your controller action to:
[HttpPost]
public async Task<IActionResult> Refresh(Card card)
{
return RedirectToAction("Index", card.Day);
}

I can not configure the route

I created a simple search engine with a controller that has a method that will accept the student parameter
this is my razor page code
<form method="post">
<div class="row form-group text-center">
<div class="col-md-3">
<input placeholder="Город" class="form-control" asp-for="#Model.Profession" />
</div>
<div class="col-md-2">
<input placeholder="Город" class="form-control" asp-for="#Model.City" />
</div>
<div class="col-md-2">
<input placeholder="Курс" class="form-control mdl-textfield__input" asp-for="#Model.Course" />
</div>
<div class="col-md-2">
<input placeholder="Специализация" class="form-control" asp-for="#Model.Specialization" />
</div>
<div class="col-md-2">
<input type="submit" value="Поиск" class="btn btn-primary " />
</div>
</div>
</form>
this is UserModel
public List<Student> Students { get; set; }
public string Profession { get; set; }
public string City { get; set; }
public int Course { get; set; }
public string Specialization { get; set; }
my controllers GET and POST
[Route("Index")]
[HttpGet]
public IActionResult Index()
[Route("Index")]
[HttpPost]
public IActionResult Index(UserModel model)
after search my rout Search/Index without parametrs. how to create rout like Search/Index/Profession=Coder/City=London/Course=4/Specialization=Code . my route is static and i can`t go to back or copy url. but i catch Document Expired
sorry my bad English.
Below is a basic example
[RoutePrefix("Search")] //place this routeprefix since "Search' is common
public class TestController: Controller
{
[Route("Index")] // "Search/Index" route for GET
[HttpGet]
public IActionResult Index()
[Route("Index")] // "Search/Index" route for POST
[HttpPost]
public IActionResult Index(UserModel model)
Now for Search/Index/Profession=Coder/City=London/Course=4/Specialization=Code.
firstly as per my understanding it should be as below.
Please check carefully.
Search/Index?Profession=Coder&City=London&Course=4&Specialization=Code.
Explanation about the above route. After Index it contains ? which suggests that querystring follows after ?. Also Profession=Coder is one pair of querystring and is followed with & suggesting that there is another querstring which is City=London, followed by & suggesting that there is another querstring which is Course=4, henceforth.
And the route defined is as below
[Route("Index/{Profession=Profession}/{City=City}/{Course=Course}/{Specialization=Specialization}")]
[HttpGet]
public IActionResult Profession(string Profession,string City,int Course,string Specialization)

How Can I Get ViewData in PartialView in Razor Pages

I'm Using Razor Pages For my App, in one part of my app I've used a partial view here is my codes;
public class Permission
{
[Key]
public int PermissionId { get; set; }
public string PermissionTitle { get; set; }
public int? ParentID { get; set; }
}
public class IndexModel : PageModel
{
public PartialViewResult OnGetCreateRole()
{
var ListPermission = permissionService.AllPermission();
return new PartialViewResult()
{
ViewName = "_PCreateRole", // partial's name
ViewData = new ViewDataDictionary<List<Permission>>(ViewData,
ListPermission)
};
}
}
ViewData is a List of Permission class and i've sent ViewData to partial but i dont know how to get ViewData, also my partial use another model, below is my partial:
#model ToMVC.DataLayer.Entities.User.Role
<div class="row">
<div class="col-md-12">
<form asp-page="CreateRole" method="post">
<div class="form-group">
<label class="control-label">Title</label>
<input asp-for="RoleTitle" class="form-control"/>
<p><span class="text-danger" asp-validation-for="RoleTitle"></span></p>
</div>
<div class="form-group">
<input type="submit" value="submit" class="btn btn-primary" />
</div>
//this part needs ViewData
#foreach (var item in ViewData)
{
}
</form>
</div>
</div>
I want to use ViewData in Foreach loop.
A better solution than ViewData would be to simply make a new ViewModel class containing all the information you need for a view.
public class UserRoleAndPermissions{
public UserRoleAndPermissions(){
Permissions = new List<Permissions>();
}
public List<Permission> Permissions {get;set;}
public ToMVC.DataLayer.Entities.User.Role Role {get;set;}
}
And your view
//check your namespace here - this is just an example
#model ToMVC.DataLayer.UserRoleAndPermissions
<div class="row">
<div class="col-md-12">
<form asp-page="CreateRole" method="post">
<div class="form-group">
<label class="control-label">Title</label>
<input asp-for="RoleTitle" class="form-control"/>
<p><span class="text-danger" asp-validation-for="RoleTitle"></span></p>
</div>
<div class="form-group">
<input type="submit" value="submit" class="btn btn-primary" />
</div>
#foreach (var item in Model.Permissions)
{
}
</form>
</div>
</div>

mvc form cannot create an abstract class

I have a form with 2 select box. But when I click the submit button, there's an error saying "Cannot create an abstract class". I have no idea what is going wrong here
#using (Html.BeginForm("Add", "Admin")) {
<input type="submit" value="Add" class="btn btn-warning small-text custom-btn" />
<div class="select-box">
<select name="users[]" multiple size="35">#{ Html.RenderAction("UserList", "GroupsAndUsers"); }</select>
</div>
<div class="select-box">
<p class="blue-text bold-text">Groups</p>
<select name="group" size="35">#{ Html.RenderAction("GroupList", "GroupsAndUsers"); }</select>
</div>
<input type="hidden" name="RedirectToUrl" value="~/GroupsAndUsers/AddUsers" />
}
Admin/Add
[HttpPost]
public ActionResult Add(Array userIDs, int groupID, string RedirectToUrl)
{
return Redirect(RedirectToUrl);
}
Array is an abstract class, so MVC has no idea which specific Array implementation to create when binding the parameters. Try something like:
public ActionResult Add(int[] userIDs, int groupID, string RedirectToUrl)

Resources