Change value of EditorFor on DropDownFor value change - c#

I am trying to make an online bank website(for learning ASP.NET MVC).I have a class Account
class Account
{
int account_id;
String account_number;
decimal balance;
}
and I have a model for transaction.
public class MakeTransactionModel
{
[Required]
public String AccountFrom { get; set; }
[Required]
public String AccountTo { get; set; }
public Decimal OrignalBalance { get; set; }
[Required]
public Decimal Amount { get; set; }
[Required]
public String TransactionFor { get; set; }
}
Then in controller, i am putting accounts in ViewBag.
ViewBag.account_from = new SelectList(db.Accounts, "account_id", "account_number");
In View, I created a drop down for showing all accounts
#Html.DropDownListFor(u => u.AccountFrom, (SelectList)ViewBag.account_from, htmlAttributes: new { #class = "form-control", #id = "AccountFrom", onchange=#"
#Model.OrignalBalance = 1000; // I tried this but did not work
" })
Now , I am trying to show balance of selected account in an EditorFor
#Html.EditorFor(model => model.OrignalBalance, new { htmlAttributes = new { #id="OrignalBalance", #class = "form-control", disabled = "disabled", #readonly = "readonly" } })
I have all accountsin ViewBag and I am showing that accounts number in drop down (those accounts also have balance in it). I am trying to change value of EditorFor on DropDownFor value change but still unable to do that. I tried to do that using jquery, but i don't know can I use LINQ in jquery
My jquery code is
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('#AccountFrom').change(function () {
var selectedValue = $('#AccountFrom').text();
$('#OrignalBalance').val(#{new BankEntities().Accounts.SingleOrDefault(acc => acc.account_number == $('#AccountFrom').text())}); // I am trying to do this
});
});
}
)
</script>
It will be good if i find a good solution to do that, so I can update EditorFor on change event.
Thank you.

You should make an ajax call and pass the account number and get the amount from the server.
$(function()
{
$('#AccountFrom').change(function() {
var accountId= $('#AccountFrom').val();
var url="#Url.Action("Balance","Account")";
$.post(url+"?accountNumber="+accountId,function(response){
if(response.Status==="success")
{
$("#OrignalBalance").val(response.Balance);
}
else
{
alert("Invalid Account");
}
});
});
});
Assuming you have an action method to return the balance
[HttpPost]
public ActionResult Balance(string accountNumber)
{
//Of course you want to authorize the call
var db=new BankEntities();
var a= db.Accounts.FirstOrDefault(x=> x.account_number ==accountNumber);
if(a!=null)
{
return Json( new { Status="success", Balance=a.Balance });
}
else
{
return Json( new { Status="error"});
}
}
If you do not wish to make an action method and the ajax way, What you can do is, Create a dictionary of your account number and the balance and pass that as part of your view model and in your razor view, set that to a js object and in the change event you can query the js dictionary to get the value.
Also, I recommend to NOT use ViewBag to transfer data between your action method and your view for rendering the dropdown. You should add a strongly typed property to handle that.
So let's add some new properties to your view model.
public class MakeTransactionModel
{
// Your other existing properties here
public Dictionary<string,decimal> AccountBalances { set; get; }
// These 2 properties are for rendering the dropdown.
public int FromAccountId { set; get; }
public List<SelectListItem> FromAccounts { set; get; }
}
And in your GET action, fill this property with account number and corresponding balance value.
public ActionResult Transfer()
{
var vm = new MakeTransactionModel();
vm.AccountBalances = new Dictionary<string, decimal>();
// Hard coded for demo. You may read it from your db tables.
vm.AccountBalances.Add("CHECKING0001", 3450.50M);
vm.AccountBalances.Add("SAVINGS0001", 4450.50M);
//load the data for accounts.pls change to get from db
vm.FromAccounts = new List<SelectListItem>
{
new SelectListItem { Value="CHECKING0001", Text="Checking" },
new SelectListItem { Value="SAVINGS0001", Text="Saving" }
};
// to do : Load other properties also
return View(vm);
}
And in your razor view, serialize this property and set to a js object.
#model MakeTransactionModel
#using(Html.BeginForm())
{
#Html.DropDownListFor(s=>s.FromAccountId,Model.FromAccounts,"Select")
#Html.EditorFor(model => model.OrignalBalance,
new { #id="OrignalBalance", #class = "form-control",
disabled = "disabled", #readonly = "readonly" } )
<input type="submit" />
}
#section Scripts
{
<script>
var balanceDict = #Html.Raw(Newtonsoft.Json.JsonConvert
.SerializeObject(Model.AccountBalances));
$(function () {
$('#FromAccountId').change(function() {
var accountId= $('#AccountFrom').val();
var v = balanceDict[accountId];
$("#OrignalBalance").val(v);
});
});
</script>
}

It may not seem like it, but this is pretty broad. Basic rundown, you'll either have to:
Serialize all accounts and balances into JSON and store them client-side:
This is more code than is appropriate here, but you could use JSON.net to get JSON for new BankEntities().Accounts.ToList() (something you should be getting from your controller code, by the way, not in your view), then set a window variable to that in your JavaScript, and call upon that whenever the value changes.
Untested, but something like:
var balances = #Html.Raw(JsonConvert.SerializeObject(new BankEntities()
.Accounts
// Filter by logged in user
.ToDictionary(c => c.account_number, c.balance));
$(document).ready(function () {
$(function () {
$('#AccountFrom').change(function () {
var selectedValue = $('#AccountFrom').text();
$('#OrignalBalance').val(balances[selectedValue]);
});
});
}
Introduce an API call performed through AJAX to get balances whenever the value changes.
Shyju beat me to this one, but it's probably a better way to do it, as long as you're comfortable introducing an API element. It's kind of advanced for first learning MVC, but it's not too complicated.
This is what I'd do in a production application (although I'd do it with Web API), but for just playing, the first option is a little quicker, and probably easier to understand and debug fully if you're just getting started.
The confusion here comes from where code is executed. Your script can't refer to the BankEntities because it's running client-side, as compared to server side.

JQuery knows nothing about LINQ, since it is client based. So, I suggest making an ajax request when the account from gets changed.
for example, in the view, make the ajax call
<script type="text/javascript">
$(document).ready(function() {
$('#AccountFrom').change(function() {
var selectedAccountNumber = $('#AccountFrom option:selected').text();
$.ajax({
url: "/Accounts/GetAccountBalance",
type: "POST",
dataType: "json",
data: { accountNumber: selectedAccountNumber },
success: function (
$('#OrignalBalance').val(data.Balance);
}
});
});
});
</script>
and have the following in the controller (let's say that you have a controller called Accounts)
public ActionResult GetAccountBalance(string accountNumber)
{
var account = db.Accounts.SingleOrDefault(a => a.account_number == accountNumber);
// add validation logic for account not exits
return Json(new { AccountNumber = accountNumber, Balance = account.balance });
}

Related

pass query results to ajax callback

I am making a live search, where a user types something inside a text box and then via ajax results are fetched and added to a ul and in this specific case I am looking for usernames, so if a username is johnny and the user types in jo then johnny should come up and so on.
I have the ajax js code, a post method and a list model view of users, I am now trying to return the list but doesn't seem to be working.
my js:
$("input#searchtext").keyup(function (e) {
var searchVal = $("input#searchtext").val();
var url = "/profile/LiveSearch";
$.post(url, { searchVal: searchVal }, function (data) {
console.log(data);
});
});
LiveSearch view model
public class LiveSearchUserVM
{
public LiveSearchUserVM()
{
}
public LiveSearchUserVM(UserDTO row)
{
FirstName = row.FirstName;
LastName = row.LastName;
}
public string FirstName { get; set; }
public string LastName { get; set; }
}
the post method
[HttpPost]
public List<string[]> LiveSearch(string searchVal)
{
// Init db
Db db = new Db();
List<LiveSearchUserVM> usernames = db.Users.Where(x => x.Username.Contains(searchVal)).Select(x => new LiveSearchUserVM(x)).ToList();
return usernames;
}
So basically I want to return a list (or something else) of columns that contain a specific string, and pass all the results to javascript thru ajax callback.
To return the result as JSON alter your method to the following:
[HttpPost]
public JsonResult LiveSearch(string searchVal)
{
// Init db
Db db = new Db();
List<LiveSearchUserVM> usernames = db.Users.Where(x => x.Username.Contains(searchVal)).Select(x => new LiveSearchUserVM(x)).ToList();
return Json(usernames);
}
you can use like this . The idea is to use success funtion
$.ajax({
url : ""/profile/LiveSearch"",
type: "POST",
data : searchVal ,
success: function(data)
{
//data - response from server
},
error: function ()
{
}
});
and return JsonResult from Post method

.NET use partial view multiple times

my UI has a text box and a button, everytime I add a new element I need to show the list in the same view. I'm using partial view so I need to keep loading this partial view everytime I add a new element to my list. how can I modify my code to achieve that?
View
#Html.TextBoxFor(m => m.emailsAdded, new { #class = "form-control wide", placeholder = "Email ID", type = "email", Name = "txtEmail" }
<button id="thisButton">Add</button>
<div id="content"></div>
<script>
$(document).ready(function() {
$("#thisButton").on("click", function () {
var val = $('#emailsAdded').val();
$.ajax({
url: "/Admin/UpdateEmailList?email="+val,
type: "GET"
})
.done(function(partialViewResult) {
$("#content").html(partialViewResult);
});
});
});
</script>
Model
public class ABC
{
public IEnumerable<string> emailsAdded { get; set; }
}
Controller
[HttpGet]
public ActionResult UpdateEmailList(string email)
{
if (Session["emails"] == null)
{
List<string> aux1 = new List<string>();
aux1.Add(email);
Session["emails"] = aux1;
}
else
{
List<string> aux2 = new List<string>();
aux2 = (List<string>)Session["emails"];
aux2.Add(email);
Session["emails"] = aux2;
}
var abc = new ABC
{
emailsAdded = (List<string>)Session["emails"]
};
return PartialView("_EmailsListPartialView", abc);
}
Partial view
#using project.Models
#model project.Models.ABC
<table class="tblEmails">
#foreach (var emails in Model.emailsAdded)
{
<tr><td>#emails.ToString()</td></tr>
}
</table>
With my code I'm able to reload my div and add the new element, when doesn't work for the second time....how can I modify my code so I can keep adding stuff?
SOLUTION:
I updated my controller to show how I resolved this issue. Not really sure if it is the best way to do it, but at least helped me to resolve.
I'm storing the list of emails in Session["emails"] and every time I add a new email to the list, I just update it a pass it to a new list with all the records and at the end return the partial view.

ModelState is coming up as invalid?

I'm working on a MVC5 Code-First application.
On one Model's Edit() view I have included [Create] buttons to add new values to other models from within the Edit() view and then repopulate the new value within DropDownFors() on the Edit().
For this first attempt, I am passing a model_description via AJAX to my controller method createNewModel():
[HttpPost]
public JsonResult createNewModel(INV_Models model)
{
// model.model_description is passed in via AJAX -- Ex. 411
model.created_date = DateTime.Now;
model.created_by = System.Environment.UserName;
model.modified_date = DateTime.Now;
model.modified_by = System.Environment.UserName;
// Set ID
int lastModelId = db.INV_Models.Max(mdl => mdl.Id);
model.Id = lastModelId+1;
//if (ModelState.IsValid == false && model.Id > 0)
//{
// ModelState.Clear();
//}
// Attempt to RE-Validate [model], still comes back "Invalid"
TryValidateModel(model);
// Store all errors relating to the ModelState.
var allErrors = ModelState.Values.SelectMany(x => x.Errors);
// I set a watch on [allErrors] and by drilling down into
// [allErrors]=>[Results View]=>[0]=>[ErrorMessage] I get
// "The created_by filed is required", which I'm setting....?
try
{
if (ModelState.IsValid)
{
db.INV_Models.Add(model);
db.SaveChangesAsync();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(
new { ID = model.Id, Text = model.model_description },
JsonRequestBehavior.AllowGet);
}
What I cannot figure out is why my ModelState is coming up as Invalid?
All properties are being specified before the ModelState check; the Model is defined as follows:
public class INV_Models
{
public int Id { get; set; }
[Required(ErrorMessage = "Please enter a Model Description.")]
public string model_description { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime created_date { get; set; }
[Required]
public string created_by { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime modified_date { get; set; }
public string modified_by { get; set; }
}
EDIT:
Added View code:
Input Form:
<span class="control-label col-md-2">Type:</span>
<div class="col-md-4">
#Html.DropDownListFor(model => model.Type_Id, (SelectList)ViewBag.Model_List, "<<< CREATE NEW >>>", htmlAttributes: new { #class = "form-control dropdown" })
#Html.ValidationMessageFor(model => model.Type_Id, "", new { #class = "text-danger" })
</div>
<div class="col-md-1">
<div class="btn-group">
<button type="button" class="btn btn-success" aria-expanded="false">CREATE NEW</button>
</div>
</div>
SCRIPT:
$('#submitNewModel').click(function () {
var form = $(this).closest('form');
var data = { model_description: document.getElementById('textNewModel').value };
$.ajax({
type: "POST",
dataType: "JSON",
url: '#Url.Action("createNewModel", "INV_Assets")',
data: data,
success: function (resp) {
alert("SUCCESS!");
$('#selectModel').append($('<option></option>').val(resp.ID).text(resp.Text));
alert("ID: " + resp.ID + " // New Model: " + resp.Text); // RETURNING 'undefined'...?
form[0].reset();
$('#createModelFormContainer').hide();
},
error: function () {
alert("ERROR!");
}
});
});
When you cannot quickly deduce why your ModelState validation fails, it's often helpful to quickly iterate over the errors.
foreach (ModelState state in ModelState.Values.Where(x => x.Errors.Count > 0)) { }
Alternatively you can pull out errors directly.
var allErrors = ModelState.Values.SelectMany(x => x.Errors);
Keep in mind that the ModelState is constructed BEFORE the body of your Action is executed. As a result, IsValid will already be set, regardless of how you set your model's properties once you are inside of the Controller Action.
If you want the flexibility to manually set properties and then re-evalute the validity of the object, you can manually rerun the validation inside of your Action after setting the properties. As noted in the comments, you should clear your ModelState before attempting to revalidate.
ModelState.Clear();
ValidateModel(model);
try
{
if (ModelState.IsValid)
{
db.INV_Models.Add(model);
db.SaveChangesAsync();
}
}
...
As an aside, if the model is still not valid ValidateModel(model) will throw an exception. If you'd like to prevent that, use TryValidateModel, which returns true/false instead:
protected internal bool TryValidateModel(Object model)
You should not be using a hack like ModelState.Clear() nor is TryValidateModel(model); required. Your issue stems from the fact you have a [Required] attribute on both your created_date and created_by properties but you don't post back a value, so they are null and validation fails. If you were to post back a more complex model, then you would use a view model which did not even have properties for created_date and created_by (its a Create method, so they should not be set until you post back).
In your case a view model is not necessary since your only posting back a single value ( for model-description) used to create a new INV_Models model.
Change the 2nd line in the script to
var data = { description: $('#textNewModel').val() };
Change your post method to
[HttpPost]
public JsonResult createNewModel(string description)
{
// Initialize a new model and set its properties
INV_Models model = new INV_Models()
{
model_description = description,
created_date = DateTime.Now,
created_by = System.Environment.UserName
};
// the model is valid (all 3 required properties have been set)
try
{
db.INV_Models.Add(model);
db.SaveChangesAsync();
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json( new { ID = model.Id, Text = model.model_description }, JsonRequestBehavior.AllowGet);
}
Side notes:
I suggest modified_date be DateTime? (nullable in database
also). You are creating a new object, and are setting the
created_date and created_by properties, but setting
modified_date and modified_by properties does not seem
appropriate (it hasn't been modified yet).
I suspect you don't really want to set created_by to
System.Environment.UserName (it would be meaningless to have
every record set to administrator or whatever UserName of the
server returns. Instead you need to get users name from Identity
or Membership whatever authorization system you are using.
The model state is calculated when the binding from your post data to model is done.
The ModelState.IsValid property only tells you if there are some errors in ModelState.Errors.
When you set your created date you will need to remove the error related to it from ModelState.Errors

jQuery .serialize() issue

I am having a strange issue when serializing a form to post back to a controller method. Some of the fields being passed are null (in the case of strings or nullable values) or zero (in the case of numeric values). For instance, with this simple configuration:
ViewModel:
public class HomeViewModel
{
public int FakeId { get; set; }
public string StringDataValue { get; set; }
public int IntegerDataValue { get; set; }
public HomeViewModel() { }
public HomeViewModel(int fakeId)
{
FakeId = fakeId;
StringDataValue = "This is some string data";
IntegerDataValue = 42;
}
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
HomeViewModel viewModel = new HomeViewModel(15);
return View(viewModel);
}
[HttpPost]
public JsonResult PostData(HomeViewModel model)
{
return JsonResult
{
Data = new
{
FakeId = model.FakeId,
StringData = model.StringDataValue,
IntegerData = model.IntegerDataValue
}
};
}
}
View:
#model WebApplication1.Models.HomeViewModel
#{
ViewBag.Title = "Home Page";
}
#using(Html.BeginForm())
{
#Html.HiddenFor(m => m.FakeId)
<div>
Fake ID: #Html.DisplayFor(m => m.FakeId)
</div>
<div>
String Data: #Html.TextBoxFor(m => m.StringDataValue)
</div>
<div>
Integer Data: #Html.TextBoxFor(m => m.IntegerDataValue)
</div>
<button id="btnPost">Post</button>
}
#section scripts
{
<script type="text/javascript">
$(function () {
$("#btnPost").on("click", function (e) {
e.preventDefault();
var model = $("form").serialize();
console.log(model);
$.post("PostData", JSON.stringify(model))
.success(function (d) {
console.log(d);
})
.error(function () {
console.log("error");
})
})
})
</script>
}
If I click the Post button I get this output for the two console.log() lines:
console.log(model): FakeId=15&StringDataValue=This+is+some+string+data&IntegerDataValue=42
console.log(d):
Object {FakeId: 0, StringData: "This is some string data", IntegerData: 0}
As you can see only the StringDataValue actually made it to the controller. However, if I add #Html.Hidden("dummy") in the view just above the hidden field for Model.FakeId then I get the following output:
console.log(model):
dummy=&FakeId=15&StringDataValue=This+is+some+string+data&IntegerDataValue=42
console.log(d):
Object {FakeId: 15, StringData: "This is some string data", IntegerData: 0}
That's a little better, but the IntegerDataValue still didn't make it to the controller. However, if I add #Html.Hidden("dummy2") somewhere after where the Model.IntegerDataValue is shown in the view I get the following output:
console.log(model):
dummy=&FakeId=15&StringDataValue=This+is+some+string+data&IntegerDataValue=42&dummy2=
console.log(d):
Object {FakeId: 15, StringData: "This is some string data", IntegerData: 42}
Now all of my view model values are being passed to the controller properly. I just don't understand why I have to put the dummy fields in to make it happen. It took me a long time to figure out why I was getting incomplete data in the controller methods until I realized what was happening.
Is it just me? Can anyone else duplicate this behavior? Am I missing something?
Take out JSON.stringify and try that. So something like
<script type="text/javascript">
$(function () {
$("#btnPost").click(function(e) {
e.preventDefault();
var model = $("form").serialize();
console.log(model);
$.post("Home/PostData", model)
.success(function(d) {
console.log(d);
})
.error(function() {
console.log("error");
});
});
});
</script>

Mvc3 and Jquery Multiselect, sending values to server not working?

I am trying to use Jquery Multiselect plugin from Beautiful site and MVC3 together to send values to server. As shown in example from Darin the key is to create MultiSelectModelBinder class that will, I guess, recognize values send from client, because the multiselect plugin uses the [] notation to send the selected values to the server. My aproach is a little diferent, i fill dropDownList from my controller and not the model, keeping the model clean, and also been able to fill the list from Database. I used Darins example to create MultiSelectModelBinder and register it,in the model binder in Application_Start(). My problem is that I always keep getting empty Model back to my controller, here is the code:
MODEL:
public class PersonsSearchModel
{
public string Person { get; set; }
public string Company { get; set; }
//here is my Cities collection
public IEnumerable<string> Cities { get; set; }
}
VIEW:
#model MyNamespace.Model.PersonsSearchModel
#using (Ajax.BeginForm("Search", "Persons", new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "results",
LoadingElementId = "progress"
},
new { #id = "searchFormPerson" }
))
{
<span>
#Html.TextBoxFor(x => Model.Person, new { #class = "halfWidth"})
</span>
<span>
#Html.TextBoxFor(x => Model.Company, new { #class = "halfWidth"})
</span>
<span>
#Html.ListBoxFor(x => x.Cities, Model.Items, new { #id="combobox1"})
</span>
<input name="Search" type="submit" class="searchSubmit" value="submit" />
}
CONTROLLER:
public ActionResult Index()
{
var listCities = new List<SelectListItem>();
listCities.Add(new SelectListItem() { Text = "Select one...", Value = "" });
listCities.Add(new SelectListItem() { Text = "New York", Value = "New York" });
listCities.Add(new SelectListItem() { Text = "Boston", Value = "Boston" });
listCities.Add(new SelectListItem() { Text = "Miami", Value = "Miami" });
listCities.Add(new SelectListItem() { Text = "London", Value = "London" });
ViewBag.Cities = listCities;
return View();
}
public class MultiSelectModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var model = (PersonsSearchModel)base.BindModel(controllerContext, bindingContext);
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "[]");
if (value != null)
{
return value.RawValue;
}
return model;
}
}
Here the data from client sholud arive, butt is always null?
public PartialViewResult Search(PersonsSearchModel psm)
{
var person = psm.Person;
var company = psm.Company;
var city = psm.Cities.ElementAt(0);
return GetResultPartialView(city);
}
GLOBAL.asax.cs
protected void Application_Start()
{
//...
//model binder
ModelBinders.Binders.Add(typeof(IEnumerable<string>), new
FinessenceWeb.Controllers.PersonsController.MultiSelectModelBinder());
}
JQUERY
$("#combobox1").multiSelect();
I had the same issue, although your provided solution still works. There is another way of doing it with less effort.
Actually defaultModelbinder does bind to multiple selected values if you can change your input parameter to List<inputparameter> and change the line #Html.DropDownListFor to #Html.ListBoxFor.
The key difference between these 2 controls is, First one being a single selection box and second one being a multiple selector.
Hope this helps some one having the same issue.
Well... After looking into DOM, and Jquery plugin, turns out the plugin gives the select element, atribute name, current id, so they are the same, and the form, well.. look's at the name attr. So solution wolud be:
$("#Cities").multiSelect();
Cheers!

Categories

Resources