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
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 currently use MVC dropdown list for displaying my dropdown lists. I am looking to move my entire page to JS and web api's. The current code functions and works fine with my controller. I have some sample code that works for main table on this API but Looking to see if I can get it to function the same way I use the MVC dropdown plugins but with TypeAhead.js
Current Code for StanceType DropDownList:
<div class="row">
<div class="col-sm-4 form-group">
#Html.LabelFor(m => m.Stances.Name) #Html.TextBoxFor(m => m.Stances.Name, new { #class = "form-control col-lg" })
</div>
<div class="col-sm-4 form-group">
#Html.LabelFor(m => m.Stances.StancesTypesId) #Html.DropDownListFor(m => m.Stances.StancesTypesId, new SelectList(Model.StancesTypes, "Id", "Name"), "Select Stance Type", new { #class = "form-control col-lg" })
</div>
<div class="col-sm-4 form-group">
#Html.LabelFor(m => m.Stances.BrandsId) #Html.DropDownListFor(m => m.Stances.BrandsId, new SelectList(Model.Brands, "Id", "Name"), "Select Brand", new { #class = "form-control col-lg" })
</div>
</div>
Current Controller:
public ActionResult Details() {
var stancesTypes = _context.StancesTypes.ToList();
var priority = _context.Priority.ToList();
var brands = _context.Brands.ToList();
var viewModel = new StancesViewModel {
StancesTypes = stancesTypes,
Priority = priority,
Brands = brands
};
return View("Details", viewModel);
}
This is new typeAhead.js and API Controller that I am trying but it just displays the Name data from the Stances database and not the Name field for StanceTypes field.
var stances = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('StancesTypesId'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/api/stances?query=%QUERY',
wildcard: '%QUERY'
}
});
$('#stancetype').typeahead({
minLength: 0,
hightlight: true
}, {
name: 'StancesTypesId',
display: 'name',
source: stances
});
// GET /api/Stances
public IEnumerable <StancesDto> GetStances() {
//get accountid from user
string userId = User.Identity.GetUserId();
var userAccountID = _context.AccountProfile.Single(c => c.UserId == userId);
var stancesTypes = _context.StancesTypes.ToList();
var priority = _context.Priority.ToList();
var brands = _context.Brands.ToList();
var viewModel = new StancesViewModel {
StancesTypes = stancesTypes,
Priority = priority,
Brands = brands
};
return _context.Stances.ToList().Select(Mapper.Map <Stances, StancesDto> ).Where(c => c.AccountGUID == userAccountID.AccountGUID);
}
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.
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.
After reviewing many tutorials and various approaches to Cascading DropDownLists, I decided to create a ViewModel for my View and then populate my DropDownLists based on this post:
MVC3 AJAX Cascading DropDownLists
The goal here is the most basic and covered in many tutorials, but I still can't get it quite right... to populate a City dropdown based on the value of a State dropdown.
EDIT:
Since posting this request for help, I discovered Firebug (yes, that's how new I am to doing any sort of programming), and I was able to determine that I am successfully calling my controller, and pulling the necessary data. I believe the problem is the second half of my JavaScript that returns the data to my View.
Here is my View:
<label>STATE HERE:</label>
#Html.DropDownListFor(x => x.States, Model.States, new { #class = "chzn-select", id = "stateID" })
<br /><br />
<label>CITY HERE:</label>
#Html.DropDownListFor(x => x.Cities, Enumerable.Empty<SelectListItem>(), new { id = "cityID" })
Here is the JavaScript within my View, and somehow I'm not handling my results correctly once I get them:
$(function () {
$("#stateID").change(function () {
var stateId = $(this).val();
// and send it as AJAX request to the newly created action
$.ajax({
url: '#Url.Action("GetCities")',
type: 'GET',
data: { Id: stateId },
cache: 'false',
success: function (result) {
var citySelect = $('#cityID');
$(citySelect).empty();
// when the AJAX succeeds refresh the ddl container with
$.each(result, function (result) {
$(citySelect)
.append($('<option/>', { value: this.simpleCityID })
.text(this.cityFull));
});
},
error: function (result) {
alert('An Error has occurred');
}
});
});
});
Here is my controller called by the JavaScript:
public JsonResult GetCities(int Id)
{
return Json(GetCitySelectList(Id), JsonRequestBehavior.AllowGet);
}
private SelectList GetCitySelectList(int Id)
{
var cities = simpleDB.simpleCity.Where(x => x.simpleStateId == Id).ToList();
SelectList result = new SelectList(cities, "simpleCityId", "cityFull");
return result;
}
Here are my results from Firbug, which tell me I'm building and getting the data without issue, just not populating my DropDownList correctly:
[{"Selected":false,"Text":"Carmel","Value":"IN001"},{"Selected":false,"Text":"Fishers","Value":"IN002"}]
If anyone has any suggestions as to why the JavaScript fails to populate the dropdrown, please comment, thanks!
I have done this several times with something like this:
Create a partial to popolate dropdown list. Name it DropDownList and put in Shared folder of Views
#model SelectList
#Html.DropDownList("wahtever", Model)
Your create view should be something like this (skipped irrelevant parts)
<script type="text/javascript">
$(function() {
$("#StateId").change(function() {
loadLevelTwo(this);
});
loadLevelTwo($("#StateId"));
});
function loadLevelTwo(selectList) {
var selectedId = $(selectList).val();
$.ajax({
url: "#Url.Action("GetCities")",
type: "GET",
data: {stateId: selectedId},
success: function (data) {
$("#CityId").html($(data).html());
},
error: function (result) {
alert("error occured");
}
});
}
</script>
#Html.DropDownList("StateId")
<select id="CityId" name="CityId"></select>
Carefully note the Empty Select item for CityId and the call of loadLevelTwo at document.ready
And your controller should be like:
public ActionResult Create()
{
ViewBag.StateId = new SelectList(GetAllCities(), "Id", "Name");
return View();
}
public ActionResult GetCities(int stateId) {
SelectList model = new SelectList(GetCitiesOfState(stateId), "Id", "Name");
return PartialView("DropDownList", model);
}
Thank you for your assistance,
It turns out that in my JavaScript below, I was attempting to directly reference the simpleCityID and cityFull fields associated with my data model:
$.each(result, function (result) {
$(citySelect)
.append($('<option/>', { value: this.simpleCityID })
.text(this.cityFull));
Instead, I needed to keep it generic and inline with JavaScript standards of referencing Value and Text:
$.each(modelData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text