ViewModel not updating on POST - asp.net-mvc-3

I have a Controller and View which allow a user to 'checkout' the contents of a shopping cart.
All was working fine when my CheckoutController was returning an Order model to the Checkout view. However, I now want to also display the contents of the shopping cart on the Checkout view so have modified the Controller and View to use a viewmodel containing the Order and CartItems.
I have created a CheckoutViewModel and modified the GET: and POST: ActionResults to use this viewmodel.
Problem is the CheckOutViewModel is not being properly populated during the POST:
I am getting an 'Object reference not set to an instance of an object' error on this line 'checkoutViewModel.Order.Username = User.Identity.Name;' in the POST: ActionResult but I am not sure exactly what is not being instansiated.
If need be, I can post the original working coded that used the Oreder model instead of the CheckoutViewModel.
I'm sure I have some simple sturctural or syntax problem, I just can't tell what it is because I'm still trying to get my head around the best way to do things in MVC.
GET: ActionResult
//GET: /Checkout/AddressAndPayment
public ActionResult AddressAndPayment()
{
//To pre-populate the form, create a new Order object and get the ShoppingCart, populate the ViewModel and pass it to the view
var order = new Order();
order.Username = User.Identity.Name;
MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
storeDB.SaveChanges();
var cart = ShoppingCart.GetCart(this.HttpContext);
// Set up our ViewModel
var viewModel = new CheckoutViewModel
{
CartItems = cart.GetCartItems(),
CartTotal = cart.GetTotal(),
Order = order
};
// Return the view
return View(viewModel);
}
POST: ActionResult
//POST: /Checkout/AddressAndPayment
[HttpPost]
public ActionResult AddressAndPayment(FormCollection values)
{
var checkoutViewModel = new CheckoutViewModel();
TryValidateModel(checkoutViewModel);
try
{
checkoutViewModel.Order.Username = User.Identity.Name;
checkoutViewModel.Order.OrderDate = DateTime.Now;
//Save Order
storeDB.Orders.Add(checkoutViewModel.Order);
storeDB.SaveChanges();
//Process the order
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.CreateOrder(checkoutViewModel.Order);
storeDB.SaveChanges();
//Send 'Order Confirmation' email
ViewData["order"] = checkoutViewModel.Order;
UserMailer.OrderConfirmation(checkoutViewModel.Order).SendAsync();
return RedirectToAction("Complete", new { id = checkoutViewModel.Order.OrderID });
}
catch
{
//Invalid - redisplay with errors
return View(checkoutViewModel);
}
}
View
#model OrderUp.ViewModels.CheckoutViewModel
#{
ViewBag.Title = "AddressAndPayment";
}
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<h2>Pick Up Details</h2>
<fieldset>
<legend>When are you gonna be hungry?</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Order.Phone)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Order.Phone)
#Html.ValidationMessageFor(model => model.Order.Phone)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Order.PickUpDateTime)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Order.PickUpDateTime)
#Html.ValidationMessageFor(model => model.Order.PickUpDateTime)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Order.Notes)
</div>
<div class="editor-multiline-field">
#Html.EditorFor(model => model.Order.Notes)
#Html.ValidationMessageFor(model => model.Order.Notes)
</div>
</fieldset>
<input type="submit" value="Submit Order" />
}
<div style="height:30px;"></div>
<h3>
<em>Review</em> your cart:
</h3>
<table>
<tr>
<th>
Menu Item
</th>
<th>
Price (each)
</th>
<th>
Notes
</th>
<th>
Quantity
</th>
<th></th>
</tr>
#foreach (var item in Model.CartItems)
{
<tr id="row-#item.RecordID">
<td>
#Html.ActionLink(item.MenuItem.Name, "Details", "Store", new { id = item.MenuItemID }, null)
</td>
<td>
#Html.DisplayFor(modelItem => item.MenuItem.Price)
</td>
<td>
#Html.DisplayFor(modelItem => item.Notes )
</td>
<td id="item-count-#item.RecordID">
#item.Count
</td>
<td>
</td>
</tr>
}
<tr>
<td >
Total
</td>
<td id="cart-total">
#String.Format("${0:F2}", Model.CartTotal)
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>

You should use CheckoutViewModel as an input parameter to your HttpPost method and then try debug and see if you are still not getting that model populated after the form post.
[HttpPost]
public ActionResult AddressAndPayment(CheckOutViewModel checkoutViewModel)
{
TryValidateModel(checkoutViewModel);
try
{
checkoutViewModel.Order.Username = User.Identity.Name;
checkoutViewModel.Order.OrderDate = DateTime.Now;
//Save Order
storeDB.Orders.Add(checkoutViewModel.Order);
storeDB.SaveChanges();
//Process the order
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.CreateOrder(checkoutViewModel.Order);
storeDB.SaveChanges();
//Send 'Order Confirmation' email
ViewData["order"] = checkoutViewModel.Order;
UserMailer.OrderConfirmation(checkoutViewModel.Order).SendAsync();
return RedirectToAction("Complete", new { id = checkoutViewModel.Order.OrderID });
}
catch
{
//Invalid - redisplay with errors
return View(checkoutViewModel);
}
}

Related

MVC ViewModel data gets clear after posting and showing validation error

my problem it's kinda strange. So in a Index.cshtml i populate with data and in some place i use
#Html.Action("_Create")
To create a partialView where i populate with some data from the Server and with some empty fields that need to be completed for submit.
[HttpGet]
public PartialViewResult _Create()
{
var userOrder = _orderRepository.CurrentUser(User.Identity.GetUserName());
var something = new CurrentListOrderViewModel()
{
PersonName = userOrder.Select(p=>p.PersonName).FirstOrDefault(),
Funds = userOrder.Select(p=>p.Funds).FirstOrDefault(),
Order = "",
OrderCosts = 0,
Restaurant = "",
TodayOrderDate = DateTime.Now,
WindowsName = User.Identity.GetUserName()
};
return PartialView(something);
}
[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult _Create([Bind(Include = "PersonName,Funds,Order,OrderCosts,WindowsName,TodayOrderDate")]CurrentListOrderViewModel model)
{
if(ModelState.IsValid)
{
return PartialView();
}
return PartialView(model);
}
So the problem is when the page loads with HTTPGET everything goes fine, the table get's populated from the database and if i change in the _Create.cshtml the #Html.EditorFor into something else so i can disable it, i lose the data. What could be the cause? I don't really understand it.
#model FoodOrderQubizInterfaces.ViewModel.Order.CurrentListOrderViewModel
#using(Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<tr>
<td>
#Html.EditorFor(model => model.PersonName)
#Html.ValidationMessageFor(model => model.PersonName)
</td>
<td>
#Html.EditorFor(model => model.Funds, new { htmlAttributes = new { disabled = "disabled" }, })
#Html.ValidationMessageFor(model => model.Funds)
</td>
<td>
#Html.EditorFor(model => model.Order)
#Html.ValidationMessageFor(model => model.Order)
</td>
<td>
#*#Html.DropDownListFor(model => model.Restaurant,*#
<select>
<option value="1">Bigys</option>
<option value="2">Zulu</option>
</select>
</td>
<td>
#Html.EditorFor(model => model.OrderCosts)
#Html.ValidationMessageFor(model => model.OrderCosts)
</td>
<td>
#Html.EditorFor(model => model.WindowsName)
#Html.ValidationMessageFor(model => model.WindowsName)
<input type="submit" value="Save/Modify" class="btn btn-default" />
</td>
<td>
#Html.EditorFor(model => model.TodayOrderDate)
#Html.ValidationMessageFor(model => model.TodayOrderDate)
</td>
<td>
</td>
</tr>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Hope you guys can help me with some advice cause i'm out of ideas
I found the problem, after i search the web for some time. The cause was when you submit and you have the disabled attribute added it will not add to the model cause he thinks the model is disabled so the user couldn't interact with it.
So to fix it i changed from
<td>
#Html.EditorFor(model => model.Funds, new { htmlAttributes = new { disabled = "disabled" }, })
#Html.ValidationMessageFor(model => model.Funds)
</td>
To
#Html.TextBoxFor(model => model.Funds, new { #readonly = true })
And in that was it keeps the data. I hope it will help someone else with my problem

How can I make a loop to repeat my method for each item?

there is my issue. In a controller, I have this method which export my view in a file when I click a button.
public ActionResult Export(string searchString, int searchOrder = 0)
{
var user = from m in db.Orders select m;
if (!String.IsNullOrEmpty(searchString))
{
user = user.Where(s => s.ClientID.Contains(searchString));
}
Response.AddHeader("Content-Type", "application/vnd.ms-excel");
return this.View(user);
}
My Index view :
#model IEnumerable<MyApp.Models.Order>
#{
ViewBag.Title = "Index";
}
<h2>Orders Historic</h2>
<div id="orderDiv">
#using (Html.BeginForm("Export", "Historic", FormMethod.Get))
{
<p>
Generate Order with ClientID :&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
#Html.TextBox("searchString")
<input type="submit" value="GENEREMOI" />
</p>
}
</div>
And my Export view :
#model IEnumerable<KrysGroup.Models.Order>
<table cellpadding="3" cellspacing="3">
<tr>
<td width="12%" align="center">
Client Name/ID
</td>
<td width="15%" align="center">
N° Order
</td>
OTHER TD....
</tr>
#foreach (var item in Model)
{
TimeSpan result = DateTime.Now - item.OrderDate;
if (result.Days < 31)
{
<tr border="1" bgcolor="#Odd">
<td> #Html.DisplayFor(modelItem => item.Username) </td>
<td> #Html.DisplayFor(modelItem => item.OrderId) </td>
<td>
<ul style="list-style-type:none; padding:0; margin:0">
#if (item.OrderDetails != null)
{
foreach (var o in item.OrderDetails)
{
if (o.Pack == null)
{
<li> #Html.DisplayFor(modelItem => o.Product.Name) </li>
}
else
{
<li> <text>Pack</text> #Html.DisplayFor(modelItem => o.Pack.Name) </li>
}
}
}
</ul>
</td>
OTHER TD...
</table>
So, in my view, I inform in a textbox a ClientID and when I click the button, it export in a file all the fields in my table with this ClientID.
I would like to automate this action, that is to say I would like write a method or something for, when I click on the button, it executes this export() method for each clientId it meet in my table.
I hope I was clear enough, sorry for my english..
Thanks for your answers, links, tips whatever.
You can write a partial view typed to a list of Id's that loads when you click the button.
So in the controller you have a method converts what you want and returns a view that is typed to the conversion of your model.
In your main view you have a div that will be populated with a partial view after the click-event of the original button.
#Ajax.ActionLink("Name", "NameOfTheAction", "NameOfTheController",
new { id = itemId },
new AjaxOptions { HttpMethod = "Get", UpdateTargetId = "divInMainView", OnSuccess = "Do Something (js)" },
new { html-props })
How to populate is up to you, in your view

MVC 3 Razor - Form not posting back to controller

I am using MVC 3 and Razor, attempting to post a form back to a controller from a telerik window (telerik.window.create) that loads a partial view. Im not sure how to post this so ill just post the code in order of execution and explain it as I go.
First an anchor is clicked, and onClick calls:
function showScheduleWindow(action, configId) {
var onCloseAjaxWindow = function () { var grid = $("#SubscriptionGrid").data("tGrid"); if (grid) { grid.rebind(); } };
CreateAjaxWindow("Create Schedule", true, false, 420, 305, "/FiscalSchedule/" + action + "/" + configId, onCloseAjaxWindow);
}
And the CrateAjaxWindow method:
function CreateAjaxWindow(title, modal, rezible, width, height, url, fOnClose) {
var lookupWindow = $.telerik.window.create({
title: title,
modal: modal,
rezible: rezible,
width: width,
height: height,
onClose: function (e) {
e.preventDefault();
lookupWindow.data('tWindow').destroy();
fOnClose();
}
});
lookupWindow.data('tWindow').ajaxRequest(url);
lookupWindow.data('tWindow').center().open();
}
Here is the partial view that is being loaded:
#model WTC.StatementAutomation.Web.Models.FiscalScheduleViewModel
#using WTC.StatementAutomation.Model
#using WTC.StatementAutomation.Web.Extensions
#using (Html.BeginForm("Create", "FiscalSchedule", FormMethod.Post, new { id = "FiscalScheduleConfigForm" }))
{
<div id="FiscalScheduleConfigForm" class="stylized">
<div class="top">
<div class="padding">
Using fiscal year end: #Model.FiscalYearEnd.ToString("MM/dd")
</div>
<div class="padding Period">
<table border="0">
<tr>
<th style="width: 120px;"></th>
<th>Effective Date</th>
<th>Next Run</th>
<th>Start From Previous</th>
</tr>
<tr>
<td>
#Html.CheckBoxFor(m => m.HasMonthly)
<label>Monthly</label>
</td>
<td>
#{ var month = Model.GetForFiscalPeriod(FiscalPeriodStatementSchedule.FiscalPeriod.Monthly);}
#month.BaseSchedule.StartDate.ToString("MM/01/yyyy")
</td>
<td>
#month.BaseSchedule.NextScheduleRun.ToString("MM/dd/yyyy")
</td>
<td class="previous">
#(month.HasRun ? Html.CheckBoxFor(m => month.BaseSchedule.StartFromPreviousCycle, new { #disabled = "disabled", #readonly = "readonly" }) : Html.CheckBoxFor(m => month.BaseSchedule.StartFromPreviousCycle))
</td>
</tr>
<tr>
<td>
#Html.CheckBoxFor(m => m.HasQuarterly) Quarterly
</td>
<td>
#{ var quarter = Model.GetForFiscalPeriod(FiscalPeriodStatementSchedule.FiscalPeriod.Quarterly);}
#quarter.BaseSchedule.StartDate.ToString("MM/01/yyyy")
</td>
<td>
#quarter.BaseSchedule.NextScheduleRun.ToString("MM/dd/yyyy")
</td>
<td class="previous">
#(quarter.HasRun ? Html.CheckBoxFor(m => quarter.BaseSchedule.StartFromPreviousCycle, new { #disabled = "disabled", #readonly = "readonly" }) : Html.CheckBoxFor(m => quarter.BaseSchedule.StartFromPreviousCycle))
</td >
</tr>
<tr>
<td>
#Html.CheckBoxFor(m => m.HasAnnual) Annual
</td>
<td>
#{ var annual = Model.GetForFiscalPeriod(FiscalPeriodStatementSchedule.FiscalPeriod.Annual);}
#annual.BaseSchedule.StartDate.ToString("MM/01/yyyy")
</td>
<td>
#annual.BaseSchedule.NextScheduleRun.ToString("MM/dd/yyyy")
</td>
<td class="previous">
#(annual.HasRun ? Html.CheckBoxFor(m => annual.BaseSchedule.StartFromPreviousCycle, new { #disabled = "disabled", #readonly = "readonly" }) : Html.CheckBoxFor(m => annual.BaseSchedule.StartFromPreviousCycle))
</td>
</tr>
<tr>
<td>
#Html.CheckBoxFor(m => m.HasSemiAnnual) Semi-annual
</td>
<td>
#{ var semi = Model.GetForFiscalPeriod(FiscalPeriodStatementSchedule.FiscalPeriod.SemiAnnual);}
#semi.BaseSchedule.StartDate.ToString("MM/01/yyyy")
</td>
<td>
#semi.BaseSchedule.NextScheduleRun.ToString("MM/dd/yyyy")
</td>
<td class="previous">
#(semi.HasRun ? Html.CheckBoxFor(m => semi.BaseSchedule.StartFromPreviousCycle, new { #disabled = "disabled", #readonly = "readonly" }) : Html.CheckBoxFor(m => semi.BaseSchedule.StartFromPreviousCycle))
</td>
</tr>
</table>
</div>
<div class="padding StartDay">
<span>Run on day:</span>
#Html.TextBoxFor(model => model.StartDay)
<span>of every period.</span>
</div>
</div>
<div class="bottom">
<div class="padding">
<div style="float: left;">
#if (Model.ShowSuccessSave)
{
<div id="successSave" class="label">Changes saved succesfully</div>
}
#Html.ValidationSummary(true)
#Html.HiddenFor(x => x.SubscriptionId)
#Html.HiddenFor(x => x.DeliveryConfigurationId)
#Html.HiddenFor(x => x.FiscalYearEnd)
</div>
<a id="saveSchedule" class="btn" href="">Save</a>
</div>
</div>
</div>
}
<script type="text/javascript">
$(function () {
$('a#saveSchedule').click(function () {
$(this).closest("form").submit();
return false;
});
});
</script>
And finally the controller method:
[HttpPost]
public ActionResult Create(FormCollection formValues, int subscriptionId, int deliveryConfigurationId, int startDay, DateTime fiscalYearEnd)
{
if (ModelState.IsValid)
{
var selectedSchedules = GetCheckedSchedulesFromForm(formValues);
var startFromPrevious = GetFromPreviouSelections(formValues);
this.AddModelErrors(_fiscalScheduleService.AddUpdateSchedules(selectedSchedules, subscriptionId, deliveryConfigurationId, startDay, startFromPrevious));
}
return new RenderJsonResult { Result = new { success = true, action = ModelState.IsValid ? "success" : "showErrors",
message = this.RenderPartialViewToString("_FiscalScheduleConfigForm",
BuildResultViewModel(deliveryConfigurationId, subscriptionId, fiscalYearEnd, ModelState.IsValid)) } };
}
As you can see I am using jQuery to post back to the controller, which I have done on several occasions in the applicaiton, this seems to work fine normally. But with this form, for some reason it is not posting back or stepping into the Create method at all. I am speculating that it has something to do with the parameters on the controller method. But I am fairly new to MVC (coming from ASP.NET world) so Im not really sure what I am doing wrong here. Any help would be greately appreciated!
I was able to get it to post to the controller by modifying the textboxfor for the startDay:
Changed from:
#Html.TextBoxFor(model => model.StartDay)
To:
#Html.TextBoxFor(model => model.StartDay, new { id = "startDay" })
My guess is that you're running on a virtual directory in IIS? That url you're generating is likely the culprit.
Hit F12, check out the network tab (and enable tracing) and see what it's trying to request.
Instead of building the link through text, why not use #Url.Action()? You could store this in an attribute on the a tag (like in an attribute called data-url, for example) and then use that info to make your call. It's pretty easy to pull out the attribute with jQuery, something like this:
$('.your-link-class').click(function(){
var url = $(this).attr('data-url');
// proceed with awesomesauce
});
Would something like that work for you?
[shameless self plug] As far as the controller action signature goes, you might want to look into model binding if you can. One simple class and many of your headaches will go away. You can read more here, read the parts on model binding. There are downloadable samples for different approaches.
Cheers.

How to pass a list of objects instead of one object to a POST action method

I have the following GET and POST action methods:-
public ActionResult Create(int visitid)
{
VisitLabResult vlr = new VisitLabResult();
vlr.DateTaken = DateTime.Now;
ViewBag.LabTestID = new SelectList(repository.FindAllLabTest(), "LabTestID", "Description");
return View();
}
//
// POST: /VisitLabResult/Create
[HttpPost]
public ActionResult Create(VisitLabResult visitlabresult, int visitid)
{
try
{
if (ModelState.IsValid)
{
visitlabresult.VisitID = visitid;
repository.AddVisitLabResult(visitlabresult);
repository.Save();
return RedirectToAction("Edit", "Visit", new { id = visitid });
}
}
catch (DbUpdateException) {
ModelState.AddModelError(string.Empty, "The Same test Type might have been already created,, go back to the Visit page to see the avilalbe Lab Tests");
}
ViewBag.LabTestID = new SelectList(repository.FindAllLabTest(), "LabTestID", "Description", visitlabresult.LabTestID);
return View(visitlabresult);
}
Currently the view display the associated fields to create only one object,, but how i can define list of objects instead of one object to be able to quickly add for example 10 objects at the same “Create” request.
My Create view look like:-
#model Medical.Models.VisitLabResult
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#section scripts{
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>VisitLabResult</legend>
<div class="editor-label">
#Html.LabelFor(model => model.LabTestID, "LabTest")
</div>
<div class="editor-field">
#Html.DropDownList("LabTestID", String.Empty)
Your viewModel
public class LabResult
{
public int ResultId { get; set; }
public string Name { get; set; }
//rest of the properties
}
Your controller
public class LabController : Controller
{
//
// GET: /Lab/ns
public ActionResult Index()
{
var lst = new List<LabResult>();
lst.Add(new LabResult() { Name = "Pravin", ResultId = 1 });
lst.Add(new LabResult() { Name = "Pradeep", ResultId = 2 });
return View(lst);
}
[HttpPost]
public ActionResult EditAll(ICollection<LabResult> results)
{
//savr results here
return RedirectToAction("Index");
}
}
Your view
#model IList<MvcApplication2.Models.LabResult>
#using (Html.BeginForm("EditAll", "Lab", FormMethod.Post))
{
<table>
<tr>
<th>
ResultId
</th>
<th>
Name
</th>
</tr>
#for (int item = 0; item < Model.Count(); item++)
{
<tr>
<td>
#Html.TextBoxFor(modelItem => Model[item].ResultId)
</td>
<td>
#Html.TextBoxFor(modelItem => Model[item].Name)
</td>
</tr>
}
</table>
<input type="submit" value="Edit All" />
}
Your view will be rendered as follows, this array based naming convention makes it possible for Defaultbinder to convert it into ICollection as a first parameter of action EditAll
<tr>
<td>
<input name="[0].ResultId" type="text" value="1" />
</td>
<td>
<input name="[0].Name" type="text" value="Pravin" />
</td>
</tr>
<tr>
<td>
<input name="[1].ResultId" type="text" value="2" />
</td>
<td>
<input name="[1].Name" type="text" value="Pradeep" />
</td>
</tr>
If I understand your question correctly,
you want to change your view to be a list of your model object #model List, then using a loop or however you wish to do it, create however many editors you need to for each object
then in your controller your receiving parameter of create will be a list of your model instead too.

Partial postback of page with dropdownlist using AJAX on MVC3 page EF4

I have a dropdownlist which lists Country names
When user select any country from dropdown list.Based on the country selection, I need data(AgencyName, AgencyAddr,Pincode) to be loaded from database and fill the TextBoxs on the right side.The selected country in the dropdown should remain selected.
on selection change of dropdownlist ,I do not want the entire page to postback .Please help me
Here is my EF4 - ModelClasses
public class Country
{
public int CountryID { get; set; }
public string CountryName { get; set; }
}
public class AgencyInfo
{
public int CountryID { get; set; }
public string AgencyName { get; set; }
public string AgencyAddr { get; set; }
public int Pincode { get; set; }
}
Here is my MVC4 razor page Index.cshtml
#using (Ajax.BeginForm(
"Index",
"Home",
new AjaxOptions { UpdateTargetId = "result" }
))
{
#Html.DropDownList("SelectedCountryId", Model.CountryList, "(Select one event)")
}
<div id=’result’>
<fieldset>
<legend>Country Details: </legend>
<div>
<table>
<tr>
<td>
<span>Country Name </span>
<br />
#Html.EditorFor(model => model.Countries.Name)
#Html.ValidationMessageFor(model => model. Countries.Name)
</td>
<td>
<span>Agency Name </span>
<br />
#Html.EditorFor(model => model.AgencyInfo.AgencyName)
#Html.ValidationMessageFor(model => model.AgencyInfo.AgencyName)
</td>
</tr>
<tr>
<td>
<span>Address Info </span>
<br />
#Html.EditorFor(model => model. AgencyInfo.Address)
#Html.ValidationMessageFor(model => model. AgencyInfo.Address)
</td>
<td>
<span>Pin Code </span>
<br />
#Html.EditorFor(model => model. AgencyInfo.PinCode)
#Html.ValidationMessageFor(model => model. AgencyInfo.PinCode)
</td>
</tr>
<tr>
<td>
<input type="submit" value="Modify" /><input type="submit" value="Delete" />
</td>
<td>
<input type="submit" value="Save" /><input type="submit" value="View Resources" />
</td>
</tr>
</table>
</div>
</fieldset>
</div > #end of result div#
Any suggestions ? Thank you
You want to use ajax.
Add an event handler to monitor the selection change. When the drop down changes, get the current country and send the ajax request. When the ajax request returns update the DOM with jQuery.
Example view:
<p id="output"></p>
<select id="dropDown"><option>Option 1</option>
<option>Option 2</option></select>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$("#dropDown").change(function () {
var selection = $("#dropDown").val();
var dataToSend = {
country: selection
};
$.ajax({
url: "home/getInfo",
data: dataToSend,
success: function (data) {
$("#output").text("server returned:" + data.agent);
}
});
});
});
</script>
Example controller method:
public class HomeController : Controller
{
[HttpGet]
public JsonResult GetInfo(string country)
{
return Json(new { agent = country, other = "Blech" }, JsonRequestBehavior.AllowGet);
}
}
Some other examples:
adding a controller method to handle ajax request:
http://www.cleancode.co.nz/blog/739/ajax-aspnet-mvc-3
calling ajax and updating DOM:
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax2

Resources