MVC3 Text Box Text change Event - asp.net-mvc-3

I have the following scenario, using mvc3:
I have a database table which holds a RecordID, RecordName and RecordType. Displayed are three text boxes, one for each of the fields mentioned previously.
My Question is, when i enter a RecordID into the relevant text box, i want to be able to show the RecordName and RecordType for that particular RecordID. How can i achieve this?

In View:
#Html.TextBoxFor(model => model.RecordId)
#Html.TextBoxFor(model => model.RecordName)
#Html.TextBoxFor(model => model.RecordType)
<script language="javascript">
$('#RecordId').change(function(){
var recordId = this.value;
$.getJSON("/MyController/GetRecordById",
{
id: recordId
},
function (data) {
$('RecordName').val(data.Name);
$('RecordType').val(data.Type);
});
});
</script>
In Controller:
public JsonResult GetRecordById(int id)
{
var record = recordRepository.GetById(id);
var result = new {
Name = record.Name,
Type = record.Type
}
return Json(result, JsonRequestBehavior.AllowGet);
}

Related

pass input text from view to controller

i know there are a lot questions like this but i really cant get the explanations on the answers... here is my view...
<script type="text/javascript" language="javascript">
$(function () {
$(".datepicker").datepicker({ onSelect: function (dateText, inst) { },
altField: ".alternate"
});
});
</script>
#model IEnumerable<CormanReservation.Models.Reservation>
#{
ViewBag.Title = "Index";
}
<h5>
Select a date and see reservations...</h5>
<div>
<div class="datepicker">
</div>
<input name="dateInput" type="text" class="alternate" />
</div>
i want to get the value of the input text... there's already a value in my input text because the datepicker passes its value on it... what i cant do is to pass it to my controller... here is my controller:
private CormantReservationEntities db = new CormantReservationEntities();
public ActionResult Index(string dateInput )
{
DateTime date = Convert.ToDateTime(dateInput);
var reservations = db.Reservations.Where(r=>r.Date==date).Include(r => r.Employee).Include(r => r.Room).OrderByDescending(r => r.Date);
return View(reservations.ToList());
}
i am trying to list in my home page the reservations made during the date the user selected in my calender in my home page....
I don't see a Form tag in your View...or are you not showing the whole view? hard to tell.. but to post to your controller you should either send the value to the controller via an ajax call or post a model. In your case, your model is an IEnumerable<CormanReservation.Models.Reservation> and your input is a date selector and doesn't look like it is bound to your ViewModel. At what point are you posting the date back to the server? Do you have a form with submit button or do you have an ajax call that you aren't showing?
Here is an example of an Ajax request that could be called to pass in your date
$(function () {
$(".datepicker").onselect(function{
searchByDate();
})
});
});
function searchbyDate() {
var myDate = document.getElementById("myDatePicker");
$.ajax({
url: "/Home/Search/",
dataType: "json",
cache: false,
type: 'POST',
data: { dateInput: myDate.value },
success: function (result) {
if(result.Success) {
// do something with result.Data which is your list of returned records
}
}
});
}
Your datepicker control needs something to reference it by
<input id="myDatePicker" name="dateInput" type="text" class="alternate" />
Your action could then look something like this
private CormantReservationEntities db = new CormantReservationEntities();
public JsonResult Search(string dateInput) {
DateTime date = Convert.ToDateTime(dateInput);
var reservations = db.Reservations.Where(r=>r.Date==date).Include(r => r.Employee).Include(r => r.Room).OrderByDescending(r => r.Date);
return View(reservations.ToList());
return Json(new {Success = true, Data = reservations.ToList()}, JsonRequestBehaviour.AllowGet());
}
Update
If you want to make this a standard post where you post data and return a view then you need to make changes similar to this.
Create a ViewModel
public class ReservationSearchViewModel {
public List<Reservation> Reservations { get; set; }
public DateTime SelectedDate { get; set; }
}
Modify your controller actions to initially load the page and then be able to post data return the View back with data
public ActionResult Index() {
var model = new ReservationSearchViewModel();
model.reservations = new List<Reservation>();
return View(model);
}
[HttpPost]
public ActionResult Index(ReservationSearchViewModel model) {
if(ModelState.IsValid)
var reservations = db.Reservations.Where(r => r.Date = model.SelectedDate).Include(r => r.Employee).Include(r => r.Room).OrderByDescending(r => r.Date);
}
return View(model)
}
Modify your view so that you have a form to post to the Index HttpPost action
#model CormanReservation.Models.ReservationSearchViewModel
<h5>Select a date and see reservations...</h5>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
#Html.EditorFor(model => model.SelectedDate)
#Html.EditorFor(model => model.Reservations) // this may need to change to a table or grid to accomodate your data
<input type="submit" value="Search" />
}

call to controller to populate text box based on dropdownlistfor selection using Ajax

I have a dropdown and when I select an item from it, I want to pass on the selected value to a function in a controller, query the db and auto load a text box with query results.
How do I use Ajax to make that call to the controller when there is onclick() event on the dropdown?
My dropdown and textbox in my aspx page is:
<%: Html.DropDownListFor(model => model.ApplicationSegmentGuid, Model.ApplicationSegment)%>
<%: Html.TextAreaFor(model => model.EmailsSentTo, false, new { style = "width:500px; height:50px;" })%>
My function in controller is
public ActionResult AsyncFocalPoint(Nullable<Guid> ApplicationSegmentGuid)
{
string tempEmail = UnityHelper.Resolve<IUserDirectory>().EmailOf();
tempEmail = "subbulakshmi.kailasam#lyondellbasell.com" + tempEmail;
IList<string> EmailAddresses = new List<String>();
using (TSADRequestEntities context = UnityHelper.Resolve<TSADRequestEntities>())
{
EmailAddresses = context.FOCALPOINTs.Where(T => T.APPLICATIONSEGMENT.ItemGuid == ApplicationSegmentGuid && T.FlagActive)
.Select(T => T.Email).ToList();
}
foreach (string emailAddress in EmailAddresses)
tempEmail = tempEmail + ";" + emailAddress;
return Json(tempEmail, JsonRequestBehavior.AllowGet);
}
You could give your dropdown an id and url:
<%= Html.DropDownListFor(
model => model.ApplicationSegmentGuid,
Model.ApplicationSegment,
new { id = "myddl", data_url = Url.Action("AsyncFocalPoint") }
) %>
and then subscribe to the .change() event of the dropdown list unobtrusively and trigger the AJAX request:
$(function() {
$('#myddl').change(function() {
// get the selected value of the ddl
var value = $(this).val();
// get the url that the data-url attribute of the ddl
// is pointing to and which will be used to send the AJAX request to
var url = $(this).data('url');
$.ajax({
url: url,
type: 'POST',
data: { applicationSegmentGuid: value },
success: function(result) {
// TODO: do something with the result returned by the server here
// for example if you wanted to show the results in your textarea
// you could do this (it might be a good idea to override the id
// of the textarea as well the same way we did with the ddl):
$('#EmailsSentTo').val(result);
}
});
});
});

Read selected value of drop down in controller

Requirment: I have a drop down and a table on my cshtml page. The drop down displays a list of vendors and the details corresponding to selected vendor are displayed in table. I am submitting the form using jquery when the value of the drop down changes.
Problem: How to cath selected value of drop down in controller?
Code:
#Html.DropDownList("VendorList", new SelectList(Model.vendorList, "vendorId", "vendorName"))
#using (Html.BeginForm("VendorDetails", "VendorLookUp", FormMethod.Post, new { id = "vendorDetailsForm" }))
{
<div class="margin-10-top" >
<table id= "VendorDetail" class="VendorDetail">
........ details of vendor.........
</table>
</div>
}
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$('#VendorList').change(function () {
$('#vendorDetailsForm').submit();
});
});
</script>
the code in my controller is:
[AcceptVerbs("POST")]
public ActionResult SearchResult(FormCollection collection)
{
try
{
string vendorName = collection["searchItem"].ToString();
vendorName = vendorName.Trim();
List<Vendor> vendorList = Queries.compiledVendorQuery(dbContext, vendorName).ToList<Vendor>();
if(vendorList.Count() == 0)
return View("EmptySearch");
Vendor selectedVendor = vendorList[0];
VendorDetails vendorDeatils = Queries.compiledVendorDetailsQuery(dbContext, selectedVendor.vendorId.ToString()).FirstOrDefault();
VendorResult vendorResult = new VendorResult();
vendorResult.vendorList = vendorList;
vendorResult.vendorDetails = vendorDeatils;
return View(vendorResult);
}
catch (Exception e)
{
return View("EmptySearch");
}
}
[AcceptVerbs("POST")]
public ActionResult VendorDetails(FormCollection collection)
{
**here comes the control after postback
require value of the selected item**
Vendor selectedVendor = ??
VendorDetails vendorDeatils = Queries.compiledVendorDetailsQuery(dbContext, selectedVendor.vendorId.ToString()).FirstOrDefault();
VendorResult vendorResult = new VendorResult();
vendorResult.vendorDetails = vendorDeatils;
return View(vendorResult);
}
Since you're not really using the FormCollection, you could just use an int (or whatever the ID is on your model) in your action method:
[HttpPost]
public ActionResult VendorDetails(int vendorId = 0)
{
Vendor selectedVendor = // Load from your data source using vendorId
... // Do the rest of your work
}
In your HTML, move your #Html.DropDownListFor() into your form, rename it to the argument name, then submit the form as normal. Since the display doesn't seem to have any affect on what gets sent to the server, I would pull this out and just leave the #Html.DropDownListFor() in the form:
#using (Html.BeginForm("VendorDetails", "VendorLookUp", FormMethod.Post, new { id = "vendorDetailsForm" }))
{
#Html.DropDownList("vendorId", new SelectList(Model.vendorList, "vendorId", "vendorName"))
}
<div class="margin-10-top" >
<table id= "VendorDetail" class="VendorDetail">
........ details of vendor.........
</table>
</div>
<script type='text/javascript'>
$(document).ready(function () {
$('#vendorId').change(function () {
$('#vendorDetailsForm').submit();
});
});
</script>
Edit
Take a look at this article about MVC's model binding for an idea of how vendorId gets injected from the submitted form. Basically, the binder will match property names with the name attribute (by default) to your model. In this case, our model is just an int.

jQueryUI autocomplete with MVC3: posting autocompleted value

I'm new to jQueryUI+MVC3 (Razor) and this is probably a trivial question, anyway: I am trying to let autocomplete work so that as soon as an item is selected from the popup my form is submitted back to its Index action.
Here are my steps (this fake sample refers to an index of Person's):
1) I create a PersonFilter wrapper like:
public sealed class PersonFilter
{
public string LastName { get; set; }
public int RoleId { get; set; }
// ... etc.
}
2) I create a PersonList model to hold the list of Person's together with some filters.
3) my Index action is like (it is serving data to a view using MvcContrib data grid, whence page and sort):
public ViewResult Index(int? page, GridSortOptions sort, PersonFilter filter)
{
var persons = _repository.GetPersons(filter);
if (sort.Column != null)
persons = persons.OrderBy(sort.Column, sort.Direction);
ViewBag.Sort = sort;
PersonList list = new PersonList
{
persons = persons.AsPagination(page ?? 1, 10),
LastName = filter.LastName,
RoleId = filter.RoleId,
Roles = _repository.GetRoles(),
// ...
};
ViewBag.Filter = filter;
return View(list);
}
I also have a FindPerson action which gets a LastName parameter and is used to autocomplete on the person name filter.
4) my view relevant code:
...
#model PersonList
...
#using (Html.BeginForm("Index", "Person", FormMethod.Post, new { id = "TheForm" }))
{
...
<input type="text" id="LastName"/>
#Html.DropDownListFor(m => m.RoleId, new SelectList(Model.Roles, "Id", "Title", 0),
new {onchange = "document.getElementById('TheForm').submit();"})
...
}
<script type="text/javascript" language="javascript">
$(function () {
$("#LastName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Person/FindPerson", type: "POST", dataType: "json",
data: { LastName: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.LastName, value: item.LastName, id: item.Id };
}));
}
});
},
select: function (event, ui) {
$("#LastName").val(ui.item.value);
//alert($("#LastName").val());
$(this).closest("form").submit();
}
});
});
</script>
Now the autocomplete works fine, I can type and get a popup and select an item from it; in this case my select handler is called, and the form is posted to the Index action. Anyway, this action does not get its filter LastName member filled (its name is equal to the autocompleted input), while it regularly gets its RoleId and other members filled as expected.
I tried explicitly setting the LastName input value as shown in the select handler (even if this should be redundant), but nothing changes. Yet, if I uncomment the alert line I can view the correct value shown. If I break into the Index action, the filter LastName is not set and if I add the FormCollection object in its parameters I find NO key named LastName. A key appears only if I add a hidden field like:
#Html.HiddenFor(m => m.LastName)
but this is just a test for finding out what's wrong with my autocompleted input. Could anyone explain what I'm doing wrong here?
You should give a name to your LastName textbox:
<input type="text" id="LastName" name="LastName" />
Also I would recommend you using helpers to generate it. If you used helpers you wouldn't have had such problems:
#Html.TextBoxFor(x => x.LastName)
Without a name nothing will be posted to the server.

MVC3 Razor conditional loading

I want to implement following:
A combobox/DropDownListFor named "target" in a view. It contains (e.g.) A and B as choice.
In the same view I have another combobox named "medium". Its content depends on the chosen target, e.g.:
- if target = "A", combobox "medium" will show 1 and 2 as choice.
- if target = "B", combobox "medium" will show 3 and 4 as choice.
I have implemented combobox "target" successfully, but I don't know how to implement combobox "medium" related to "target". If I am not wrong, the logic should be: get the chosen targetid -> find all medium related to the targetid -> fill combobox "medium" with the result.
Here is snippet of my current view (combobox "target"):
<div class="editor-label">
#Html.LabelFor(model => model.TargetId)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.TargetId, (ViewData["targets"] as SelectList).MakeSelection(Model.TargetId))
</div>
Thx in advance.
You could use the javascript OnChange of the first drop to do an ajax call to obtain the values based from the choice A or B.
Then with the JSon response you get from the controller you fill the dropdown "Medium"
in the JS file do something like this:
$(document).ready(function () {
$("#target").change(function () { GetMediumValues("#target", "#medium"); });
});
function ClearDrop(objSource) {
$(objSource).empty();
}
function GetMediumValues(objSource, objDest) {
var url = '/mySite/GetMediumValues/';
$.getJSON(url, { id: $(objSource).val() }, function (data) {
ClearDrop(objDest);
$.each(data, function (index, optionData) {
$(objDest).append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>");
});
});
}
While in the controller
public ActionResult GetMediumValues(string id)
{
int myId = 0;
int.TryParse(id, out myId);
var select = new SelectList(repository.GetMediumValues(myId), "Id", "Name");
return Json(select, JsonRequestBehavior.AllowGet); //allow get needed to allow get calls
}

Resources