How do I post response from radiobutton groups back to controller?
Scenarios:
Patient1 oAccept oReject
Patient2 oAccept oReject
#using (Html.BeginForm("SaveResponse", "Account", null,
FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#model List<Patients>
foreach(var patient in Model)
{
<label>#Html.RadioButton(patient.PatientID, "True")Accept</label>
<label>#Html.RadioButton(patient.PatientID, "False")Reject</label>
}
}
Lets say, user clicks Accept for patient1 and then for patient2. Let say, he clicks Reject. In controller, action method how do I accept these responses. Responses like "Patient1 True" "Patient2 False" SaveResponse(....)?
Thanks for help.
Related
I know that this question might have been already on this site, but there are some different things in my approach because I use #Html.EditFor and #Html.DropDownList.
So I have a drop down list and when I choose the ID there I want to retrieve some information from the DB then populate some fields in the current form. I know that I should use JS but I don't know how.
View:
#model TestApp.Dtos.InsertDto
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="col-md-9">
#Html.DropDownListFor(model => model.Category, new SelectList(Model.ListOfCategory, "Text", "Text"), "-- Please select --", htmlAttributes: new { #class = "form-control"});
</div>
<div class="col-md-9">
#Html.EditFor(model => model.Car, new{htmlAttributes = new { #class = "form-control" }});
</div>
#*And then the form continues with other fields and after that the submit button *#
}
You can use ajax to get data from backend,and put the result data into somewhere you want.Here is a simple demo to get a selectListItem from backend and put it into a div.If you want to do something more complex,you need to share the structure of InsertDto,and explain clearly what kind of data you will get from db and explain what does populate some fields in the current form mean?
View:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="col-md-9">
#Html.DropDownListFor(model => model.Category, new SelectList(Model.ListOfCategory, "Text", "Text"), "-- Please select --", htmlAttributes: new { #class = "form-control" ,#onchange = "getData()" })
</div>
<div id="dbdata">
</div>
}
js:
<script>
function getData() {
$.ajax({
type: "POST",
data: { Category: $("#Category").val() },
url: '/B/GetData',
}).done(function (result) {
$("#dbdata").html("the selected value is " + result.text);
});
}
</script>
Model:
public class InsertDto
{
public string Category { get; set; }
public List<SelectListItem> ListOfCategory { get; set; }
}
controller:
public IActionResult Index(string id)
{
InsertDto i = new InsertDto { ListOfCategory = new List<SelectListItem> { new SelectListItem { Text = "t1" }, new SelectListItem { Text = "t2" }, new SelectListItem { Text = "t3" } } };
return View(i);
}
public SelectListItem GetData(string Category)
{
return new SelectListItem { Text = Category, Value = Category + "value" };
}
result:
I want to send multiple selected column values to controller. I don't have issues in sending one column data to controller but having trouble sending more than one column data.
View:
#using (Html.BeginForm("GridView", "Home", FormMethod.Post))
{
#Html.Grid(Model).Columns(columns =>
{
columns.Add()
.Titled("<input type=checkbox class=ckbCheckAll />")
.Encoded(false)
.Sanitized(false)
.SetWidth(10)
.RenderValueAs(c => Html.CheckBox("assignChkBx", false, new { #class = "checkBoxClass", value = c.AccountNumber})).SetWidth(10);
//.RenderValueAs(c => Html.CheckBox("checked", false, new {#class = "checkBoxClass"})).SetWidth(10);
columns.Add(c => c.AccountNumber).Titled("ACCOUNTNUM").SetWidth(20);
}).WithPaging(8);
Controller:
[HttpPost]
public ActionResult GridView(FormCollection form)
{
SelectedListOfClaimants slc = new SelectedListOfClaimants();
var checkbox = form.GetValues("assignChkBx");
}
In the view where I have value = c.AccountNumber (One of my columns), I need to add two more columns and send all three columns data to my controller.
My view:
Checkbox AccountNumber Date Name
[] 1 5/12/2001 John
[] 2 5/10/2003 Paul
[] 3 5/11/2018 Tom
I want to validate the entered username and password entered in the textboxes present in a form without Postback/Refresh. I know I am gonna need Javascript or AJAX for this purpose, but somebody please guide me through this like refer me to any tutorial or please explain me the code here.
My present code without this feature looks like this:
#using(Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.TextBoxFor(u => u.PPNumber, new { #class = "form-control", type = "number", placeholder = "Enter Number",#min="1" })
#Html.ValidationMessageFor(u => u.PPNumber)
#Html.TextBoxFor(u => u.Password, new { #class = "form-control", type = "Password", placeholder = "Password" })
#Html.ValidationMessageFor(u => u.Password)
<input type="submit" value="Login" class="btn btn-primary btn-block" />
}
You can use ajax.
When user submits the form, you need to hijack that event in javascript and stop that(prevent the normal full page form submit) and instead make an ajax call to the action method with the form data. This action method should have code to verify the user credentials and can return a JSON data structure which has a status property which says whether the credential validation is successful or not. You can inspect this response in your ajax call's success/done callback and act accordingly.
Here is a quick sample using jQuery $.post method.
Give an Id to your form so that we can use that to wire up the submit event.
#using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id="loginForm"))
{
#Html.TextBoxFor(u => u.PPNumber)
#Html.TextBoxFor(u => u.Password, new { #class = "form-control", type = "Password"})
<input type="submit" value="Login" class="btn btn-primary btn-block" />
}
and the javascript code to hijack the submit event and do an ajax post instead.
$(function () {
$("#loginForm").submit(function(e) {
e.preventDefault();
$.post($(this).attr("action"), $(this).serialize())
.done(function(response) {
if (response.status === 'success') {
alert("Login successful.Do something else now");
} else {
alert("Login failed");
}
});
});
});
Assuming your Login action method in AccountController will return a Json response with a status property.
public ActionResult Login(string PPNumber,string password)
{
if(PPNumber=="thisIsDemo" && password=="ButDoTheActualCheck")
{
return Json(new { status = "success" });
}
return Json(new { status = "failed" });
}
Here i just hard coded the usrename /password check to 2 static values. You can change that to check it against your db table/whatever your credentials checking mechanism is.
let's suppose I have a form like this:
#using (Ajax.BeginForm("ChangePassword", "User", new { area = "UserSettings" }, new
AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "ShowMessage('Password successfully changed')"
}, null))
{
#Html.TextBoxFor(m => m.Password, new { placeholder = "Password", #class = "form-control", #type = "password" })<br />
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger", #style = "float:right;" })
#Html.TextBoxFor(m => m.PasswordConfirm, new { placeholder = "Confirm password", #class = "form-control", #type = "password" })<br />
#Html.ValidationMessageFor(model => model.PasswordConfirm, "", new { #class = "text-danger", #style = "float:right;" })
<button type="submit" class="btn btn-primary">Change Password</button>
}
Essentially it's a form to change a password with validation setup in place.
Now my Question here is, in the case where I have an action like this:
[HttpPost]
[ActionName("ChangePassword")]
public ActionResult ChangePassword(MyObjectClass model)
{
if(!ModelState.IsValid)
{
return View(model);
}
else{
ViewBag.MyData = // some data here;
return View();
}
}
The questions that I have are:
When I return a View with all data in it, how do I actually then inject that returned data into the user's DOM that the user can see the changes reflected when OnSuccess method is called? Where is the "data" object that I can inject into like in done function in jQuery( .done(function(data)))?
What is the easiest way here to transfer now all the data from my controller action into the OnSuccess method and actually let the user see the outcome of the method that they called?
Can someone help me out with this ? What is the best way to solve this issue ?
I used to work with pure jQuery before and I Was doing this in this manner:
$.post("/linktomymethod",{/*some parameters*/).done(function(data){
// then inject the returned data into the browser's DOM
}));
If you want to use #Ajax.BeginForm(), then you specify the UpdateTargetId property of AjaxOptions, for example
<div id="changepassword">
#using (Ajax.BeginForm(..., new AjaxOptions { UpdateTargetId = "changepassword" }, null))
{
....
}
<div>
which would replace your <form> element with the view returned by your ChangePassword() method. Note also that your should be returning a PartialView.
However, you should stick with the $.ajax() methods as these give you far more flexibility. Typically you handle the forms .submit() event, check the .valid() method (and cancel the ajax call if not so client side validation messages are displayed), and then update the DOM with the partial view that the method returns.
Replace your #using (Ajax.BeginForm(..) { code with a simple
<div id="changepassword">
#using (Html.BeginForm()) {
....
and add the following script
var url = '#Url.Action("ChangePassword", "User", new { area = "UserSettings" })';
$('form').submit(function (ev) {
ev.preventDefault(); // prevent the default submit
if (!$(this).valid()) { // check if the data is valid
return; // exit the function
}
var formdata = $(this).serialize();`
$.post(url, formdata, function(response) {
$('changepassword').html(response);
});
});
To improve performance further, your could just return a JsonResult containing the invalid properties and their associated error, and update the placeholder elements generated by #Html.ValidationMessageFor(). You controller code would be
if (!ModelState.IsValid)
{
var errors = ModelState.Keys.Where(k => ModelState[k].Errors.Count > 0).Select(k => new { propertyName = k, errorMessage = ModelState[k].Errors[0].ErrorMessage });
return Json(errors);
}
// Save data
return Json(null);
In the success callback, you can then loop through the collection, find the corresponding ValidationMessageFor() placeholder based on the property name, and add the error message and appropriate class names.
I'm gonna try to keep the code to a minimum here.
In my MVC3 application using c# I have a form in a partial view and the submit button in the main view. I have the [required] attribute on the model properties used in the partial view and also rules set out in an associated javascript file.
But when a user a doesn't enter any data on the field in the form no validation is executed and the application continues.
I assumed the following steps would be correct.
I have the Javascript file referenced in the main view.
The form Id is referenced in this javascript file as is the input id of the submit input form the main view.
Example of model property:
[Required]
[ScaffoldColumn(true)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
[Display(Name = "Expected Return Date to Customer")]
public DateTime? ExpectedReturnedToCustomer { get; set; }
Form tag in partial view:
<form id="multipleenroutetoltslab" method="post"
Partial view is called via #{Html.RenderPartial();}
Input tag used for Submit.
<input type="submit" style="width:100%;" class="styledbutton" id="MultiSubBtn" value="Submit" />
Javascript file reference in main view (part of a bundle):
.Add("~/Scripts/CalibrationViewer/MultipleEnRouteToLtsLab.js")
Javascript file :
$(document).ready(function () {
$('#MultiSubBtn').click(function () {
$('#multipleenroutetoltslab').validate({
errorClass: 'field-validation-error',
errorPlacement: function (error, element) { //place the error method after the date picker component
var trigger = element.next('.ui-datepicker-trigger');
error.insertAfter(trigger.length > 0 ? trigger : element);
},
rules: {
SentBy: {
required: true,
maxlength: 255
},
DateSentToLtsLab: {
required: true,
dateFormat: true
},
ExpectedReturnedToCustomer: {
required: true,
dateFormat: true
}
},
The view Partial View:
#model EnRouteToLts_RecByLts
<form id="multipleenroutetoltslab" method="post">
<p>
#Html.LabelFor(m => m.SentBy)
#Html.TextBoxFor(M => M.SentBy, new { disabled = "disabled", #readonly = "readonly" })
</p>
<p>
#Html.LabelFor(m => m.DateSentToLtsLab)
#Html.TextBox("DateSentToLtsLab", Model.DateSentToLtsLab.HasValue ? Model.DateSentToLtsLab.Value.ToShortDateString() : DateTime.Now.ToShortDateString(), new { disabled = "disabled", #readonly = "readonly" })
</p>
<p>
#Html.LabelFor(m => m.ExpectedReturnedToCustomer)
#Html.TextBox("ExpectedReturnedToCustomer", Model.ExpectedReturnedToCustomer.HasValue ? Model.ExpectedReturnedToCustomer.Value.ToShortDateString() : null, new { #class = "date-picker" })
</p>
</form>
There is more code the javascript file if needed.
I placed an alert after the $('#MultiSubBtn').click(function () { and it was fired so the file is being reached but rules are not being applied.
Also it should be noted when data is entered in the form it does reach the Post action.
No errors.