I have checkboxes and select options inside a form.
<label>
<input type="checkbox" name="checkedBoxes" value="Reseller"checked />
<span>Reseller</span>
</label>
<label>
<input type="checkbox" name="checkedBoxes" value="SI" checked/>
<span>SI</span>
</label> //selects
...
Checkboxes are displayed as checked.
This is what my controller looks like:
public IActionResult combinedForm(string[] checkedBoxes, string SelectOption, string SelectOptionComp, string SelectOptionSer, string SelectOptionSoft, string SelectOptionApp)
{ //viewModel=...
var deneme = viewModel.Where(x =>x.Companies.company_type.Contains(checkedBoxes[0]));
}
How can I keep the state of checkboxes, preferably with the selected select options on view when I clicked the submit button?
Used viewbags for both
#if (((string[])ViewBag.checkedBoxes).Contains("Component provider"))
{
<label>
<input type="checkbox" name="checkedBoxes" value="Component provider" checked />
<span>Component provider </span>
</label>
}
else if (!((string[])ViewBag.checkedBoxes).Contains("Component provider"))
{
<label>
<input type="checkbox" name="checkedBoxes" value="Component provider" />
<span>Component provider </span>
</label>
}
<select style="width:100px" id="SelectOption" name="SelectOption" value="a">
<option>#Html.Label("-",(string)ViewBag.Name,new {#class = "mylabel" })</option>
Related
I have a problem with my form its not passing radio button selected value to controller but another values are passed successfully when debugging.
Please note Job.PublicSubmissionReviewed its boolean, I noticed the this Job.PublicSubmissionReviewed passed through the form at all.
What am I missing on the radio button:
Here is my form and controller, your assistance will be greatly appreciated:
<form asp-action="Review">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Job.Id" />
<div class="form-group">
<p><strong>Approve or Reject public submission</strong></p>
<div class="form-group form-check-inline">
<label class="form-check-label">
<input class="form-radio-input" name="status" value="True" type="radio" asp-for="Job.PublicSubmissionReviewed" /> Approve
</label>
</div>
<div class="form-group form-check-inline">
<label class="form-check-label">
<input class="form-check-input" name="status" value="False" type="radio" asp-for="Job.PublicSubmissionReviewed" /> Reject
</label>
</div>
</div>
<div class="form-row showapprove" id="True">
<div class="form-group col-md-6">
<label asp-for="Job.JobCategoryId" class="control-label"></label>
<select asp-for="Job.JobCategoryId" class="form-control" asp-items="ViewBag.JobCategoryId">
</select>
</div>
<div class="form-group col-md-6">
<label asp-for="Job.Name" class="control-label"></label>
<input asp-for="Job.Name" class="form-control" />
<span asp-validation-for="Job.Name" class="text-danger"></span>
</div>
<div class="form-group col-md-6">
<label asp-for="Job.JobNo" class="control-label"></label>
<input asp-for="Job.JobNo" class="form-control" />
<span asp-validation-for="Job.JobNo" class="text-danger"></span>
</div>
<div class="form-group col-md-6">
<label asp-for="Job.ContractorId" class="control-label"></label>
<select asp-for="Job.ContractorId" class="form-control" asp-items="ViewBag.ContractorId">
</select>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-outline-primary"><i class="fas fa-save" aria-hidden="true"></i> Submit</button>
</div>
</form>
public async Task<IActionResult> Review(int id, JobViewModel model)
{
if (id != model.Job.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
var job = _context.Jobs.Where(j => j.Id == id).SingleOrDefault();
if (model.Job.PublicSubmissionReviewed == true) // approve public submission
{
job.PublicSubmissionReviewed = true;
job.PublicSubmissionReviewDate = DateTime.Now;
job.Name = model.Job.Name;
job.New = true;
job.JobNo = model.Job.JobNo;
job.JobCategoryId = model.Job.JobCategoryId;
job.ContractorId = model.Job.ContractorId;
_context.Update(job);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Public));
}
else if (model.Job.PublicSubmissionReviewed == false) // reject public submission
{
job.PublicSubmissionReviewed = true;
job.PublicSubmissionReviewDate = DateTime.Now;
job.New = false;
job.PublicSubmissionRejected = true;
job.PublicSubmissionRejectedDate = DateTime.Now;
job.PublicSubmissionReviewRejectReason = model.Job.PublicSubmissionReviewRejectReason;
_context.Update(job);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Public));
}
}
catch (DbUpdateConcurrencyException)
{
if (!JobExists(model.Job.Id))
{
return NotFound();
}
else
{
throw;
}
}
}
return View(model);
}
The name HTML attribute in a form element is what will be sent to the server to identify that field once you submit the form. Razor's model binding expects a certain name for form fields, and asp-for automatically sets that name for you. Since you've manually specified a name instead, the model binder will not be able to recognize the field, and therefore will not set it in your model.
It looks like you're setting the name in order to group the radio buttons together. Since asp-for will use the same name for a given bound property, you do not need to worry about that; all radio buttons corresponding to a certain property will be grouped together.
Therefore, you can simply remove the name attribute and your code should then work fine:
<input class="form-radio-input" value="True" type="radio" asp-for="Job.PublicSubmissionReviewed" /> Approve
<input class="form-check-input" value="False" type="radio" asp-for="Job.PublicSubmissionReviewed" /> Reject
I am a new .NET programmer. I have the following input:
<input asp-for="FirstName"
id="FirstName"
class="form-control"
value="#Context.Request.Query["FirstName"]"
type="text"
readonly="readonly" />
If the textbox has data, I want the textbox to be readonly, if there is no data in the textbox, then the user can input data. Can anybody give advice?
If the textbox has data, I want the textbox to be readonly, if there
is no data in the textbox, then the user can input data. Can anybody
give advice?
According to your code and description, it seems that you want to set the textbox to be read-only based on the FirstName query string parameter. I suggest you could try to use the following code (use Razor syntax):
#model MVCDemo.Models.Customer
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="FirstName" class="control-label"></label>
#{
var value = Context.Request.Query["FirstName"].ToString();
if (string.IsNullOrEmpty(value))
{
<input asp-for="FirstName" id="FirstName" class="form-control" value="#value" type="text" />
}
else
{
<input asp-for="FirstName" id="FirstName" class="form-control" value="#value" type="text" readonly />
}
}
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
The screenshot as below:
Besides, if you want to make the textbox read-only after entering some value, you could use JQuery to add or remove the readonly attribute on the textbox.
You can do something like this
#{
var firstname= Context.Request.Query["FirstName"];
}
<input asp-for="FirstName" id="FirstName" class="form-control"
value="#Context.Request.Query["FirstName"]" type="text"
readonly="#(Context.Request.Query["FirstName"]=="" ? "False" : "True")">
I have a number of radio button groups, called Properties. A property can be things like "colour", "size", "height", and so on. The properties have options. For "colour", the options could be "Red", "Blue", and so on. When I'm posting my form, I'm able to read the Id for each individual radio button, but I haven't been able to access the group-Ids.
I'm rendering the properties like this:
for (int i = 0; i < Model.Properties.Count(); i++)
{
<div class="col-lg-3 col-md-4 col-sm-6">
<strong>#Model.Properties[i].Label</strong><br />
#foreach (var option in Model.Properties[i].Options)
{
<label style="font-weight:unset;">
#Html.RadioButtonFor(m => m.Properties[i].SelectedRadioOption, option.Id, new { id = Model.Properties[i].Id })
#option.Value
#Model.Properties[i].Unit
</label>
<br />
}
#Html.ValidationMessageFor(m => m.Properties[i].SelectedRadioOption)
</div>
}
This produces HTML like this:
<div class="col-lg-3 col-md-4 col-sm-6">
<strong>Size</strong><br />
<label style="font-weight:unset;">
<input checked="checked" data-val="true" data-val-required="The Selected property field is required." id="7012" name="Properties[0].SelectedRadioOption" type="radio" value="7025" />
34 - 36
</label>
<br />
<label style="font-weight:unset;">
<input id="7012" name="Properties[0].SelectedRadioOption" type="radio" value="7026" />
37 - 39
</label>
<br />
<span class="field-validation-valid" data-valmsg-for="Properties[0].SelectedRadioOption" data-valmsg-replace="true"></span>
</div>
<div class="col-lg-3 col-md-4 col-sm-6">
<strong>Colour</strong><br />
<label style="font-weight:unset;">
<input data-val="true" data-val-required="The Selected property field is required." id="7013" name="Properties[1].SelectedRadioOption" type="radio" value="7029" />
Black
</label>
<br />
<label style="font-weight:unset;">
<input id="7013" name="Properties[1].SelectedRadioOption" type="radio" value="7036" />
Pink
</label>
<br />
<span class="field-validation-valid" data-valmsg-for="Properties[1].SelectedRadioOption" data-valmsg-replace="true"></span>
</div>
This is the section in my controller's POST-method where I iterate through the Properties:
List<PropertyOptionForProduct> propertyOptions = new List<PropertyOptionForProduct>();
if (VMProduct.Properties != null)
{
for (var i = 0; i < VMProduct.Properties.Count(); i++)
{
propertyOptions.Add(new PropertyOptionForProduct
{
ProductId = VMProduct.Id,
ProductPropertyId = VMProduct.Properties[i].Id, // <-- This is always 0!
ProductPropertyOptionId = (int)VMProduct.Properties[i].SelectedRadioOption
});
}
}
If I select "Black" on the "Colour"-property, the object looks like this:
PropertyOptionForProduct
{
ProductId = 17008,
ProductPropertyId = 0, // <-- Why not 7013?
ProductPropertyOptionId = 7025
}
The correct value for ProductPropertyId in the above example should be 7013, which is the id-value on the radio button tag.
What am I doing wrong?
The format of what is posted back from a html <form> will be (for example) name1=value1&name2=value2 this maps to the name and the value field of your checked radiobuttons. Your code might for example example generate this post Properties[0].SelectedRadioOption=7026&Properties[1].SelectedRadioOption=7036.
The server has no idea about the id attribute in your radiobutton html. The id field is not included in the post unless you alter the post (using javascript) before it is sent. So either you need to include all identifiers in the value field perhaps separated like value="1243;34534" or you need to use javascript to include the id in the post data before it is posted.
Turns out, I'm a noob.
All I needed to add to make it work was this line of razor-code in the view:
#Html.HiddenFor(m => m.Properties[i].Id)
Now I can access the value of Properties[i].Id in the controller.
I am making an ASP.NET Core Mvc web app and am working on a search form. In the form, a user can be looked up by first name, last name, zip, and either ID, email, or phone. Whether a user is inputting ID, email, or phone is determined by a drop down list. I want to bind this to the User model I have but am not sure how to do it dynamically with the dropdown list. I am able to bind first name, last name, and zip just fine since they are not dynamic fields. Code for what I have so far for the form is below:
<form asp-action="Search">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label for="sel1">Search By:</label>
#* The dropdown menu to choose input type *#
<select class="form-control" id="sel1">
<option>ID</option>
<option>Email</option>
<option>Phone</option>
</select>
</div>
#* Where users would input information for the dropdown field *#
<div class="form-group">
<label for="id">Value:</label>
<input type="text" class="form-control clearable" id="id" Placeholder="0123456789">
</div>
<div class="form-group">
<label asp-for="FirstName">First Name:</label>
<input asp-for="FirstName" type="text" class="form-control clearable" id="firstName" Placeholder="Jane">
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LastName">Last Name:</label>
<input asp-for="LastName" type="text" class="form-control clearable" id="lastName" Placeholder="Doe">
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Zip">Zip Code:</label>
<input asp-for="Zip" type="text" class="form-control clearable" id="zipCode" Placeholder="55555">
<span asp-validation-for="Zip" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Search" class="btn btn-default" id="search" />
</div>
</form>
Then the code where the model is bound on the Search function:
public async Task<IActionResult> Search([Bind("FirstName, LastName, Zip")] Consumer consumer)
{
// Code....
}
Is there a way to dynamically bind the input for the text input with id="id" based on the dropdown menu selection? Thanks in advance.
There's two options:
Render all the fields to the page (first, last, zip, etc.), and then use JavaScript to hide/show those fields based on the selection in the drop down list. For example, if you select "First Name", then show the FirstName input and hide the others. The user then enters their keywords in that input, and when they post, it will bind to FirstName naturally.
Post the value of the drop down and a generic text input. In your action, you can then simply switch on the value of the drop down and query the right property:
IQueryable<Foo> query = db.Foos;
switch (model.MyDropDownSelection)
{
case "FirstName":
query = query.Where(x => x.FirstName.Contains(keyword));
break;
// etc.
}
I have a view where I got my Ajax.BeginForm and it submits as it should. But then I have a "save icon" and when I press that button I need the values from inside the form. The form submits presents a calculation and the save icon is suppose to save it all.
But when I press the save icon (with Url.Action("SaveExcel", "Save") I can't get the values from the textboxes. How do I do that?
My HTML:
<img src="../../Images/glyphicons_446_floppy_save.png" alt="save" id="saveIcon">
<!-- Contains forms and input for annuity calculation -->
<div class="calcInput" id="calcInput">
#using (Ajax.BeginForm("ShowDetailAnnuity", "Calculation", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "CalcDetail",
LoadingElementId = "Loader",
}))
{
<div class="calculateBox">
<label for="calcOption">Choose value to calculate:</label>
<select id="calcOption" name="calcOption" title="Choose what value you want to calculate">
<option value="PMT" id="PMT" name="PMT">Payment (PMT)</option>
<option value="I" id="I" name="I">Interest (I)</option>
<option value="FV" id="FV" name="FV">Future value (FV)</option>
<option value="PV" id="PV" name="PV">Present value (PV)</option>
</select>
</div>
<div class="calculateBox" background-color="#777777">
#Html.Label("Present value (PV)", new { #id = "pvLabel" })
#Html.TextBox("PresentValue", null, new { #class = "PresentValue" })
#Html.Label("Future value (FV)", new { #id = "fvLabel" })
#Html.TextBox("FutureValue", null, new { #class = "FutureValue" })
#Html.Label("Interest rate", new { #id = "intRateLabel" })
#Html.TextBox("InterestRate", null, new { #class = "InterestRate" }) <br /> <br />
<input type="radio" name="advanceOrArrears" id="inAdvance" value="inAdvance" /> In advance<br />
<input type="radio" name="advanceOrArrears" id="inArrears" value="inArrears" /> In arrears
</div>
<div class="calculateBox">
<label for="startDate">Start date:</label>
<input type="date" id="StartDate" name="startdate" title="Choose start date for your calculation" /><br />
#Html.Label("Payment frequency")
<select id="PmtFreq" name="PmtFreq" title="Choose the payment frequency, for example: Every month">
<option value="Monthly">Monthly</option>
<option value="Quarterly">Quarterly</option>
</select><br /><br />
#Html.Label("No of payment periods")
#Html.TextBox("PaymentPeriods")
#Html.Label("Date time convention")
<select id="DTC" name="DTC" title="Choose your Date time convention">
<option value="360/360">360/360</option>
<option value="365/365">365/365</option>
</select><br /><br />
<input type="submit" id="CalcBtn" class="calcBtn" name="SubmitBtn" value="Calculate" title="Calculate your calculation" />
</div>
}
</div>
My controller:
public class SaveController : Controller
{
public ActionResult SaveExcel(string PresentValue) //Can't get PresentValue here..
{
return View();
}
}
I have tried using the names of the textboxes as parameter in the controller, and I have also tried Request.Form["PresentValue"] but nothing of that works
Sounds like you need two submit buttons.
Try turning your save button into a submit button inside your form, so that you have:
<input type="submit" name="SubmitButton" value="Calculate"/>
<input type="submit" name="SubmitButton" value="Save"/>
And then in your controller, differentiate between which button was pressed by having something like:
public ActionResult SaveExcel(string PresentValue, string SubmitButton)
{
if(SubmitButton == "Save") .... <save code>
if(SubmitButton == "Calculate") .... <calc code>
return View();
}