I have list of html checboxes in form and I need get checked checboxes values to C# array after form sent, it is possible?
<form id="form1" action="" method="post">
#foreach (var category in ViewBag.Categories)
{
<ul>
<li>
<input type="checkbox" name="Category" value=#category["UUID"] />#category["CategoryName"]<br /> //Generate >20 checkboxes
</li>
</ul>
}
<button type="submit" formmethod="post">Search</button>
</form>
First of all change following line:
<input type="checkbox" name="Category" value=#category["UUID"] />#category["CategoryName"]<br />
to:
<input type="checkbox" name="Category" value="#category["UUID"]"/>#category["CategoryName"]<br />
and now in your action you can get it from Request object or by adding a parameter of name Category to get in the action:
[HttpPost]
public ActionResult SomeAction()
{
var checkedCategories = Request.Form["Category"];
}
or:
[HttpPost]
public ActionResult SomeAction(int[] Category)
{
}
<input type="checkbox" name="Category" value=#category["UUID"] runat="server" />#category["CategoryName"]<br />
include runat="server" in the input type. you can acess in the code behind.
Related
I'm showing the user a screen where he can check what fields he wants to get from the database. Based on the checked checkboxes I want to write a query using LINQ or lambda expression and fetch the data in ASP.NET MVC. How to do that as column selections are dynamic? For example, if only Name and Email columns are checked then get the data of those 2 columns only from the database.
Controller
public ActionResult Report()
{
return View();
}
[HttpPost]
public ActionResult Report(Employee emp)
{
List<Employee> employees = new List<Employee>();
employees = db.Employees.Select(x => new Employee()
{
// select Only those columns which are checked by the user
}).ToList();
return View();
}
View
#model IEnumerable<DynamicCheck.Models.Employee>
#{
ViewBag.Title = "EmployeeReport";
}
<h2>EmployeeReport</h2>
<form action="~/Employees/Report" method="post">
<div>
<div class="col-lg-3">
<input type="checkbox" name="Name" />
<label>Employee Name</label>
</div>
<div class="col-lg-3">
<input type="checkbox" name="Email" />
<label>Employee Email</label>
</div>
<div class="col-lg-3">
<input type="checkbox" name="Address" />
<label>Employee Address</label>
</div>
<div class="col-lg-3">
<input type="checkbox" name="Phone" />
<label>Employee Name</label>
</div>
<input type="submit" value="Submit"/>
</div>
</form>
you should to use javascript and check what columns sent to view.
and create html elements dynamically...
I had to alter a radio button to include a new value.
To do this I had to put a Dictionary inside an IDictionary. The key pulls in great for the IDictionary but the Dictionary int and string don't pull in at all.
I believe it's my front end code.
Can anyone see what I am doing wrong and provide an example on how to fix?
Action Parameter in Controller
IDictionary<String, Dictionary<int, String>>
View
<fieldset>
<legend class="sr-only">Actions</legend>
<input type="hidden" name="customerId" value="#account.CustomerId" />
<input type="hidden" name="yearSetupId" value="#account.YearId" />
<label class="radio-inline"><input type="radio" name="accountActions[#(account.CustomerId)].Key[#(account.Id)].Value" value="" checked="checked">Do nothing</label>
#{
var possibleActions = account.Balance < 0 ? new[] {
BalanceAdjustmentType.Zeroed, BalanceAdjustmentType.Issued }
: new[] { BalanceAdjustmentType.Under, BalanceAdjustmentType.Sent };
}
#foreach (var action in possibleActions)
{
<label class="radio-inline"><input type="radio" name="accountActions[#(account.CustomerId)].Key[#(account.YearId)].Value" value="#action.BalanceId">#action.Text</label>
}
</fieldset>
I didn't understand your controller parameter means actually.
But I supposed the "accountActions" in your view was the variable of your "controller parameter".
If so, then your could access the nested dict value by accountActions[Key][InnerKey].
<fieldset>
<legend class="sr-only">Actions</legend>
<input type="hidden" name="customerId" value="#account.CustomerId" />
<input type="hidden" name="yearSetupId" value="#account.YearId" />
<label class="radio-inline">
<input type="radio" name="#accountActions[account.CustomerId][account.Id]" value="" checked="checked">
Do nothing
</label>
#{
var possibleActions = account.Balance < 0
? new[] { BalanceAdjustmentType.Zeroed, BalanceAdjustmentType.Issued }
: new[] { BalanceAdjustmentType.Under, BalanceAdjustmentType.Sent };
}
#foreach (var action in possibleActions) {
<label class="radio-inline">
<input type="radio" name="#accountActions[account.CustomerId][account.YearId]" value="#action.BalanceId">
#action.Text
</label>
}
</fieldset>
I'm studying ASP.NET MVC 5. I created a View "Create". But I'm not using Razor to generate the input fields, I'm using inputs with pure html.
Create.cshtml
#model MyProject.Product
<h2>Create Product</h2>
<form method="post">
Description: <br />
<input type="text" name="Description" id="Description"/> <br />
ValueType: <br />
<input type="text" name="ValueType" id="ValueType"/>
<br />
<input type="submit" name="btSend"/>
</form>
My Controller:
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Product product)
{
if (ModelState.IsValid)
{
db.Product.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return View(product);
}
It works fine. I can create new products.
But I need to use some server-side validations with Annotations in the Model.
So, I would like to send the data and, if the model is not valid, go back to the Create with the values. I know how to put the validation messages. So, I tried this:
#model MyProject.Product
<h2>Create Product</h2>
<form method="post">
Description: <br />
<input type="text" name="Description" id="Description" value="#Model.Description"/> <br />
ValueType: <br />
<input type="text" name="ValueType" id="ValueType" value="#Model.ValueType"/>
<br />
<input type="submit" name="btSend"/>
</form>
How to bind pure input with html to model?
Why null value?
Thanks a lot.
I think you may misunderstand the razor view engine. Pages 2.0 and 3.0 (razor) does not have databinding in any way. It emulates it with the html helpers, but this is not native razor databinding. Take a look at the code behind s could of the helpers (https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Html/DefaultEditorTemplates.cs) and you will see they are just performing the work that you are hoping for.
If you don't want to use razor based form approach, you can use display validation message with Viewbag/ViewData.
[HttpPost]
public ActionResult Create(Product product)
{
if (!ModelState.IsValid)
{
//if you want to get validation message from ModelState itself, you can query from Modelstate :
string message = string.Join(" , ", ModelState.Values
.SelectMany(v => v.Errors)
.Select(e => e.ErrorMessage));
ViewData["ValidationMessage"] = "Validation Message";// you can use above variable message here
return View(product);
}
// your other implementation
}
Your view should be like this :
#model MyProject.Product
<h2>Create Product</h2>
<form method="post">
<div class="error-message">#ViewData["ValidationMessage"]</div>
Description: <br />
<input type="text" name="Description" id="Description" value="#Model.Description"/> <br />
ValueType: <br />
<input type="text" name="ValueType" id="ValueType" value="#Model.ValueType"/>
<br />
<input type="submit" name="btSend"/>
</form>
But, I would recommend to use razor based form approach if you are allowed to do so.
Update :
This is an SPA app.So it's having js file also for supporting the submit button.So I think problem is on it.Could you tell me how to modify it to support multiple kind of submit buttons ? At this moment I think it supports only for a single submit button.That is why it always get the first form's hidden field value I think.Thanks.
JS
var $loginForm = $('.login-form');
$loginForm.submit(function (e) {
e.preventDefault();
if (!$('.login-form').valid()) {
return;
}
abp.ui.setBusy(
null,
abp.ajax({
contentType: app.consts.contentTypes.formUrlencoded,
url: $loginForm.attr('action'),
data: $loginForm.serialize()
})
);
});
UI
VM
public class LoginViewModel
{
public string TenancyName { get; set; }
[Required]
public string UsernameOrEmailAddress { get; set; }
[Required]
public string Password { get; set; }
public bool RememberMe { get; set; }
}
CompanyLoginFormViewModel VM :
public class CompanyLoginFormViewModel
{
public LoginViewModel LoginViewModel { get; set; }
public List<TenantListDto> Tenants { get; set; }
}
*.cshtml page
#{
var companyLoginFormViewModel = TempData["CompanyLoginFormViewModel"] as CompanyLoginFormViewModel;
}
#foreach (var tenant in companyLoginFormViewModel.Tenants)
{
<form class="login-form" action="#Url.Action("Login")?returnUrl=#ViewBag.ReturnUrl" name="companyLoginForm" method="post">
<input type="hidden" name="usernameOrEmailAddress" value="#companyLoginFormViewModel.LoginViewModel.UsernameOrEmailAddress" />
<input type="hidden" name="password" value="#companyLoginFormViewModel.LoginViewModel.Password" />
<input type="hidden" name="rememberMe" value="true" />
<input type="hidden" name="companyUrl" value="true" />
<input type="hidden" name="tenancyName" value="#tenant.TenancyName" />
<div class="row margin-top-10">
<div class="col-xs-3">
<button type="submit" class="btn btn-success uppercase">#L("LogIn")</button>
</div>
</div>
</form>
}
Generated html
<form class="login-form" action="/Account/Login?returnUrl=/Application" name="companyLoginForm" method="post" novalidate="novalidate">
<input type="hidden" name="usernameOrEmailAddress" value="fake#gmail.com">
<input type="hidden" name="password" value="fake">
<input type="hidden" name="rememberMe" value="true">
<input type="hidden" name="companyUrl" value="true">
<input type="hidden" name="tenancyName" value="Asset_Management">
<div class="row margin-top-10">
<div class="col-xs-3">
<button type="submit" class="btn btn-success uppercase">Log in</button>
</div>
</div>
</form>
<form class="login-form" action="/Account/Login?returnUrl=/Application" name="companyLoginForm" method="post" novalidate="novalidate">
<input type="hidden" name="usernameOrEmailAddress" value="fake#gmail.com">
<input type="hidden" name="password" value="fake">
<input type="hidden" name="rememberMe" value="true">
<input type="hidden" name="companyUrl" value="true">
<input type="hidden" name="tenancyName" value="Associates">
<div class="row margin-top-10">
<div class="col-xs-3">
<button type="submit" class="btn btn-success uppercase">Log in</button>
</div>
</div>
</form>
<form class="login-form" action="/Account/Login?returnUrl=/Application" name="companyLoginForm" method="post" novalidate="novalidate">
<input type="hidden" name="usernameOrEmailAddress" value="fake#gmail.com">
<input type="hidden" name="password" value="fake">
<input type="hidden" name="rememberMe" value="true">
<input type="hidden" name="companyUrl" value="true">
<input type="hidden" name="tenancyName" value="ALL">
<div class="row margin-top-10">
<div class="col-xs-3">
<button type="submit" class="btn btn-success uppercase">Log in</button>
</div>
</div>
</form>
Post method
[HttpPost]
public virtual async Task<JsonResult> Login(LoginViewModel loginModel, string returnUrl = "", string returnUrlHash = "", bool companyUrl = false)
{
CheckModelState();
// removed for clarity
}
Question : Even though I have press the 2nd submit button,it always send the tenancyName as first submit button's value.That is Asset_Management.Could you tell me why ? Thanks.
Your problem is with the script.
var $loginForm = $('.login-form');
is a collection of all your forms, but
data: $loginForm.serialize(),
will only serialize the first one, so you always posting the vales of the first form. Modify the script to handle the buttons .click() event and get its associated form
$('.btn-success').click(function(e) {
e.preventDefault(); // if you makes the button type="button" this is not required
var form = $(this).closest('.login-form');
if (!form.valid()) {
return;
}
abp.ui.setBusy(
null,
abp.ajax({
contentType: app.consts.contentTypes.formUrlencoded,
url: form.attr('action'),
data: form.serialize()
})
);
});
Why do you even have <form> and <button> at all?
Why not create links in your foreach loop, something like this:
#Html.ActionLink("Login for " + tenant.Name, "LoginAction", new {Id=tenant.Id})
You can style these links all blue and pretty as you like using CSS afterwards.
Update1, you can pass parameters to your controller using the anonymous object. Do you see how I am passing Id? Your Action will need to accept id, see this answer: passing multiple parameters in #html.actionlink()
Update2, passing username and password like this is very bad practice. You are exposing secure credentials to the view. You should forward the user to the login page with username + password input boxes where the user will login.
I have created a webapi as follow
public OatherResponse Post([FromBody] List<Oather> oather)
{
Note that OatherResponse and Oather both are classes having some property.
Now I am trying to test this using simple html as below
<form method="post" action="http://localhost:50813/api/RegisterOather">
<input type="text" name="oather[0].OatherName" id="oather[0].OatherName" value="a3VsZGVlcA==" />
<input type="text" name="oather[1].OatherName" id="oather[1].OatherName" value="a3VsZGVlcA==" />
<input type="submit" value="Click Here" />
</form>
OatherName is a string property in Oather class. But I always get count of oather as zero.
Am I missing something.
The name attribute values should be
name="[0].OatherName"
name="[1].OatherName"