Knowing the values of check box in the controller with razor - c#

I have a asp.net mvc application with razor engine.
In a view Home i have this snippet:
<section id="form_admin">
<form action="/Super/Manipuler" method="post">
<fieldset>
<legend>Formulaire d'ajout d'un administrateur</legend>
#Html.Label("Login")
#Html.Label("Mail")
#Html.Label("Password")
#Html.Label("Name")
<br />
<br />
#if(Model != null){
foreach (Upload.Models.AdminModels admin in Model)
{
if (i == 0){
<input type="radio" checked class="radio" name="radio" value="#admin.Login" >
}
else{
<input type="radio" class="radio" name="radio" value="#admin.Login" style="margin-left:0.3px;">
}
<label id="log">#admin.Login</label>
<label id="logm">#admin.Mail</label>
<label id="logp">#admin.Password</label>
<label id="logn">#admin.Name</label>
<br />
i++;
}
}
<br />
<input type="submit" value="Editer" name="submit_button"/>
<input type="submit" value="Supprimer" name="submit_button" />
Créer un nouveau compte
</fieldset>
</form>
</section>
In the controller : the action Manipuler is the below:
public ActionResult Manipuler()
{
string buttonName = Request.Form["submit_button"];
string _login = Request.Params["radio"];
Upload.Models.AdminModels admin = new AdminModels();
Upload.Models.CompteModels.Modifiying_login = _login;
if (buttonName == "Editer") { return RedirectToAction("Edit", "Admin"); }
else { admin.Delete_admin(_login); return RedirectToAction("Home", "Super"); }
}
It's works fine but i'd like to change the radiobox to checkbox.
My question is how to know all checked box in the collection of checkbox in the action Manipuler ?

Take a look at Phil Haack's article on model binding a checkbox list. Basically, you just need to set up the HTML in a specific way (name your checkboxes the same which will then convert the various POSTed values into a list).
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

Related

URL Redirect to Variable

I am working on a method that will apply to 2 different views "/DogProfile" and "/DogProfile/Profile" I want to call this method and then have it return to the current page, as it does now for "DogProfile". However, I am having trouble identifying how to create a variable that would store the url of the page I am operating from. i.e. now if I were on the Profile view and run the page I am redirected to the "/DogProfile" page instead of back to the "DogProfile/Profile" page.
Dog Profile Controller:
public IActionResult CheckOut(string activity, int dogID)
{
var status = context.Dogs.Find(dogID);
status.CheckedOut = true;
status.Activity = activity;
status.TimeCheckOut = DateTime.Now;
context.SaveChanges();
return Redirect("/dogprofile");
}
Profile view:
#model WebApplication2.Models.Dog;
<h1>#Model.DogName</h1>
<img src="#Model.ImageSource" class="dogProfile"><img />
<br />
<br />
#if (Model.Description != null)
{
<h2>Dog Special Requirements:</h2>
<p>#Model.Description</p>
}
<form asp-controller="DogProfile" asp-action="CheckOut" method="post">
<select name="activity" id="activity">
<option value="walk">Walk</option>
<option value="furlough">Furlough</option>
<option value="bathe">Bathe</option>
</select>
<br />
<input type="submit" value="Check Out" />
<input type="hidden" name="dogID" value="#Model.Id" />
</form>
If you want to submit via the Profile page and return to the current "DogProfile/Profile" page instead of the "/DogProfile" page, you can try the following code.
[HttpPost]
public IActionResult CheckOut(string activity, int dogID)
{
var status = _context.Dogs.Find(dogID);
status.CheckedOut = true;
status.Activity = activity;
status.TimeCheckOut = DateTime.Now;
_context.SaveChanges();
return Redirect("/dogprofile/profile" + "/" + dogID);
}

How to overwrite one model property in ASP.Net core

I have a model with say 10 properties. A, B, C and so on...
Property A is an array.
For each value in array I generate one tag like this:
<div class="col-sm-10 row">
#foreach (var item in Model.A)
{
<div class="col-sm-1 right-buffer">
<i class="" aria-hidden="true">#item.Text</i>
</div>
}
</div>
When user clicks on some link I should redirect it to the same page, but with Some model property changed. For example:
Current url: my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=
with model ?name=Alex&age=20&from=fr&CurrentA=
If user clicks on <a> with text foo it should be redirected on my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=foo
then is clicks on <a> with text bar and it should be now redirected on my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=bar
So entire query string (except one parameter) should be preserved to send current model state to server while I want to set one value and redirect it to the same page but with new value.
Eventually, it should acts like postback with one extra value setted to model
Is it possible or I should use JS and perform everything myself?
Manually i solved it like this:
First, create hidden fields for every property in model:
<form asp-controller="search" asp-action="index" method="get" role="form" id="searchForm" asp-antiforgery="false">
<input asp-for="SessionId" type="hidden" name="sessionId" value="#Model.SessionId" />
<input asp-for="Quantity" type="hidden" name="quantity" value="#Model.Quantity"/>
<input asp-for="SortField" type="hidden" name="sortField" value="#Model.SortField"/>
<input asp-for="IsAscending" type="hidden" name="IsAscending" value="#Model.IsAscending" />
<input asp-for="Offset" type="hidden" name="offset" value="0" />
...
</form>
Then, use JS to replace value in hidden field and then submit form. Values from inputs will be autimatically converter in query string, so everything works fine:
function sortDocuments(sortField) {
var sField = document.getElementById('SortField');
var isDescending = document.getElementById('IsAscending');
if (sField.value === sortField) {
if (isDescending.value.toUpperCase() === 'FALSE') {
isDescending.value = 'TRUE';
} else {
sField.value = 'rank';
isDescending.value = 'FALSE';
}
} else {
sField.value = sortField;
isDescending.value = 'FALSE';
}
document.getElementById('searchForm').submit();
}
Not very elegant, but it does its job.

Having trouble in accessing posted form data (MVC)

How to access posted form data in action method and display in view
I'm creating an input wizard in MVC. There are two views, one for taking input from user and another for display the input data.
Here is the model's code:
public class Info
{
public int CustomerId { set; get; }
public double Price { set; get; }
public string name { set; get; }
}
}
Controller's Code-
public ActionResult FillCustomer()
{
return View();
}
public ActionResult DisplayCustomer(FormCollection frm)
{
Info info = new Info();
info.name = Convert.ToString( Request.Form["name"]);
info.Price = Convert.ToDouble(Request.Form["price"]);
info.CustomerId = Convert.ToInt32(Request.Form["customerid"]);
return View(info);
}
FillCustomer View's Code-
<form method="post" action="DisplayCustomer">
Name: <input type="text" id="name" /><br />
Price: <input type="text" id="price" /><br />
CustomerId: <input type="text" id="customerid" />
<br />
<input type="submit" id="btn1" />
</form>
</body>
</html>
DisplayCustomer View's Code-
<body>
<div>
Name is <%=Model.name %> and ID is <%=Model.CustomerId %>
<%if (Model.Price > 200)
{%>
Greater than 200
<%}
else %>
<%{%>Lesser than 200
<%} %>
</div>
</body>
</html>
I checked with debugger, controller is not getting posted data.
Your form's input elements should have a name attribute
<form method="post" action="DisplayCustomer">
Name: <input type="text" id="name" name="name" /><br />
Price: <input type="text" id="price" name="price" /><br />
CustomerId: <input type="text" id="customerid" name="customerid" />
<br />
<input type="submit" id="btn1" />
</form>
Now you will get form data as
Info info = new Info();
info.name = Convert.ToString( Request.Form["name"]);
info.Price = Convert.ToDouble(Request.Form["price"]);
info.CustomerId = Convert.ToInt32(Request.Form["customerid"]);
In controller, form data is received as key/value pairs. And keys are generaetd from name attributes.
You are using MVC so the parameter in DisplayCustomer method is your model passed from view, which is created implicitly by model binder. Change the type from FormCollection to Info class as following:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DisplayCustomer(Info model)
{
// you can now access to Info properties
}
This way values of Info object are populeted and I think this is what you are trying to accomplish.
I think you have missed to write a Attribute top of the DisplayCustomer function. Just write it, I hope it will work.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DisplayCustomer(FormCollection frm)
{
Info info = new Info();
info.name = Convert.ToString( Request.Form["name"]);
info.Price = Convert.ToDouble(Request.Form["price"]);
info.CustomerId = Convert.ToInt32(Request.Form["customerid"]);
return View(info);
}

calculate button pressed - retrieve rates from database

I need to link to the database (finance rates) when someone enters a number in the text box and clicks calculate that it will pull the rates from the database and display the calculation below in a 'form message'. What should I put in the homecontroller/index to link the code to the database?
Index.aspx:
<td>You wish to convert:
<input type="text" name="amount" size="30" onblur="test_ifinteger(Index.amount,'amounts')"/>
<input type="submit" name="submitter" value="calculate" />
<tr><td colspan="2">That will produce:<%=ViewData["formmessage"] %></td></tr>
Home Controller:
public ActionResult Index()
{
financeInit();
if (Request.Params["submitter"] == "calculate")
calculatepressed();
return View();
public void calculatepressed()
{
.............
}
I would wrap your fields in a form like this:
<form action="Home" method="get">
<div>
You wish to convert:
<input type="text" name="amount" size="30" id="userValue" onblur=""test_ifinteger(Index.amount,'amounts')"/>
<input type="submit" name="userSubmit" />
<br />
That will produce:<%=ViewData["formmessage"] %>
</div>
</form>
Then have your controller something like this:
public ActionResult Index()
{
int value;
if (int.TryParse(Request.Params["amount"], out value))
{
ViewData["formmessage"] = calculatepressed(value);
}
return View();
}
private string calculatepressed(int value)
{
// Do your magic here and return the value you calculate
return value.ToString();
}
If this ever expands from a simple page you might want to consider changing the form action to a post and having two different methods handling the initial view of the home page and the a view for the results of the calculation.

MVC Get Basic RadioButton checked properties through form collection

had this code in my view . The usual radio list code without helper
<br /><input type="radio" name="radioFree" id="radioFree" value="Free" checked="checked" />
<br /><input type="radio" name="radioDiscount" id="radioDiscount" value="Discount" />
And then in the controller , I have
public ActionResult Create(FormCollection collection)
{
return View();
}
How do I get which radio is checked , using the form ? Collection["radioFree"] only gave me back the radio's value . Thanks .
Solved by author
Use helpers in View
<br />#Html.RadioButton("DiscountType", "Free")
<br />#Html.RadioButton("DiscountType", "Discount")
then determine the value helpers returned from collection .
You should give both Radio buttons the same name (form name - ID can be different) and then either use the value provider, or straightforward binding. You ideally want to map the group of radios to one value.
<input type="radio" name="radioValue" id="radioFree" value="Free" checked="checked" />
<input type="radio" name="radioValue" id="radioDiscount" value="Discount" />
Binding:
public ActionResult Index(string radioValue)
{
if(radioValue == "Free")
{
}
else id(radioValue == "Discount")
{
}
}
You can also do this:
string radioValue = null;
var valueResult = ValueProvider.GetValue("radioValue");
if (valueResult != null)
{
radioValue = valueResult.AttemptedValue;
}

Categories

Resources