Pass model and extra parameter from view to an action in MVC - c#

I am trying to pass a userid to my action in controller .my action is like this as you can see here:
[HttpPost]
[Authorize(Roles = "Admin,Expert")]
public ActionResult AddExpert(AssistanceJuror assistanceJuror,int UserId)
{
User user = objUserRepository.FindBy(i => i.Id == assistanceJuror.UserId).First();
user.Enable = "فعال";
assistanceJuror.Date = DateTime.Now;
objUserRepository.Edit(user);
objUserRepository.Save();
objAssistanceJurorRepository.Add(assistanceJuror);
TempData["Message"] = "کارشناس به معاونت اختصاص داده شد";
objAssistanceJurorRepository.Save();
return RedirectToAction("IndexExpert", "Assistance");
}
So this action expect 2 parameters ,one of that is my model and another one is userId .so i need to get both values from the view my view is like this :
#using ViewModelDomain
#using Repository;
#model DomainClass.AssistanceJuror
#{
ViewBag.Title = "AddExpert";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div class="wrapper-left">
<div class="wrapper-top-addCompany">
انتساب کارشناس به معاونت
<div style="float: left; padding-left: 20px;">
<div class="divider"></div>
<div class="buttonPossion">
#Html.ActionLink("بازگشت", "Index", "Assistance", new { companyid = ViewBag.firstIdeaId }, new { #class = "buttonBlueLink" })
</div>
<div class="divider"></div>
</div>
</div>
<div class="wrapper-Member" style="padding-bottom: 30px; margin-bottom: 5px; width: 100%; min-height: 550px;">
<h2>اضافه کردن کارشناس جدید
</h2>
<br />
<br />
<br />
<div class="editor-label">
انتخاب معاونت
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.AssistanceId, (SelectList)ViewBag.listAssistance)
</div>
<div class="editor-label">
انتخاب کارشناس
</div>
#* <div class="editor-field">
#Html.DropDownListFor(model => model.userId, (SelectList)ViewBag.listDisableExpert)
</div>*#
#{
if (User.IsInRole("Expert") || User.IsInRole("Admin"))
{
<div class="wrapper-Member" style="border-top: 1px solid #d3d3d3; margin-top: 30px; width: 99.5%; border-left: 1px solid #d3d3d3; margin-right: 1px">
<div class="tab-list-company" style="margin-right: -1px; width: 180px">
<h2 style="font: normal 13px BHoma; margin-right: 10px; margin-top: 2px;">اختصاص کارشناس به معاونت
</h2>
</div>
<div class="list-company" style="border: none; width: 98%">
<table>
<thead>
<tr>
<th>نام و نام خانوادگی</th>
<th>سطح تحصیلات</th>
<th>رشته تحصیلی</th>
<th>شماره همراه</th>
<th>تلفن</th>
<th>ایمیل</th>
#if (User.IsInRole("Expert") || User.IsInRole("Admin"))
{
<th style="width: 20px;">اضافه</th>
}
</tr>
</thead>
#{
userRepository objUserRepository = new userRepository();
//var listJuror = objUserRepository.FindBy(i => i.Permission == "Juror").ToList();
List<DomainClass.User> listDisableAssistance = objUserRepository.ReturnUserByEnablePermission("غیرفعال", "Assistance");
}
#foreach (var temp in listDisableAssistance)
{
<tr>
<td>
#{
string fullName = temp.Name + " " + temp.Family;
}
#Html.DisplayFor(modelItem => fullName)
</td>
<td>
#Html.DisplayFor(modelItem => temp.EducationLevel)
</td>
<td>
#Html.DisplayFor(modelItem => temp.Field)
</td>
<td>
#Html.DisplayFor(modelItem => temp.Mobile)
</td>
<td>
#Html.DisplayFor(modelItem => temp.Tell)
</td>
<td>
#Html.DisplayFor(modelItem => temp.Email)
</td>
<td>
#using (Html.BeginForm("AddExpert", "Assistance", routeValues: new { userid = temp.Id }))
{
<input type="submit" value="" class="Add" title="اضافه کردن" />
}
</td>
</tr>
}
</table>
</div>
</div>
}
}
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
In this part
<td>
#using (Html.BeginForm("AddExpert", "Assistance", routeValues: new { userid = temp.Id }))
{
<input type="submit" value="" class="Add" title="اضافه کردن" />
}
</td>
I am trying to pass my userId to my action but it doesn't work and i get an error that says the userid is null .
Best regards

I think that the problem is that you are not sending the assistanceJuror parameter to the controller.
new { userid = temp.Id }
should be
new {assistanceJuror= value, userid = temp.Id }
but I think that AssistanceJuror is a complex type so you'll get an error. Try sending only one id (for example) and get information from database in your controller.
Something like this
public ActionResult AddExpert(string assistanceJurorId,int UserId)
{
var assistanceJuror= //get Your Variable Here;
User user = objUserRepository.FindBy(i => i.Id == assistanceJuror.UserId).First();
user.Enable = "فعال";
assistanceJuror.Date = DateTime.Now;
objUserRepository.Edit(user);
objUserRepository.Save();
objAssistanceJurorRepository.Add(assistanceJuror);
TempData["Message"] = "کارشناس به معاونت اختصاص داده شد";
objAssistanceJurorRepository.Save();
return RedirectToAction("IndexExpert", "Assistance");
}
and call it in this way from the view
#using (Html.BeginForm("AddExpert", "Assistance", routeValues: new {assistanceJurorId= model.AssistanceId, userid = temp.Id }))
In this way you are not passing the selected value of the drop down list (that is stored in model.AssistanceId variable) to the controller
assistanceJurorId= model.AssistanceId
but the initial value of the property in the model because the drop down list is made in this way
#Html.DropDownListFor(x => x.AssistanceId, (SelectList)ViewBag.listAssistance))
To send the correct value of the selected element in the drop down list I suggest you to remove the Html. BeginForm and put an ajax call to your controller only on the submit of the form. In this way you are sure that the correct value will be send.

The best approach to MVC is to create a model in your GET method, use it in your View and POST the model in the Action that accept the Post verb. So, create a model class where you add all of your property (also the userid), in the view add at the top
#model YourClassModel
and your POST method
public ActionResult AddExpert(YourClassModel model)

Related

modal problem partial view same data show but different item selected

Hi Everyone, I try to used the modal to avoid having multiple pages. but I got a problem, first, I click the view button and it will display to modal the right information; but when I click other view button instead the next data, it display the previous data.
second, after I select the view button and try to select the new shoes button (expectation must be display the new module in modal) it display the data of the previous item I select in view button:
Controller:
public ActionResult Index() //main page
{
var result = _Context.Shoeses.Include(x => x.Supply).ToList();
return View(result);
}
public ActionResult New() //create new product
{
var SupplierCategory = _Context.Suppliers.ToList();
var listOfSupplier = new ShoesViewModel
{
Supply = SupplierCategory
};
return PartialView(listOfSupplier);
}
public ActionResult Details(int id) //view selected data
{
Shoes productItem = new Shoes();
productItem = _Context.Shoeses.Find(id);
return PartialView("_Details", productItem);
}
View: Index
#model IEnumerable<ShoeInformation.Models.Shoes>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<br />
<h2>Tindahan sa Bahay ni Tatang Benjamin</h2>
<br />
<br />
//my modal
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3 class="modal-title">Details</h3>
</div>
<div class="modal-body" id="modalBody">
Testing Only
</div>
</div>
</div>
</div>
//my modal
<p>#Html.ActionLink("New Shoes", "New", "Shoes", new { id="btn_Modal"}, new { #class = "btn btn-primary btn-lg",#data_toggle="modal" ,#data_target="#myModal"})</p>
<table class="table table-striped table-hover ">
<tr>
<th>Product ID
</th>
<th>Product Code
</th>
<th>Product Name
</th>
<th>Item Size
</th>
<th>Supplier
</th>
<th>Available Quantity
</th>
<th>Unit Price (Php)
</th>
<th>Action
</th>
</tr>
#foreach (var shoes in Model)
{
<tr class="success">
<td>
#shoes.Id
</td>
<td>
#shoes.ProductCode
</td>
<td>
#Html.ActionLink(#shoes.ProductName, "Edit", "Shoes", new { id=shoes.Id})
</td>
<td>
#shoes.ItemSize
</td>
<td>
<input type="hidden" value="#shoes.Id" id="hiddenval" />
#Html.HiddenFor(x => shoes.Id)
#Html.DisplayFor(x => shoes.Supply.SupplierName)
</td>
<td>
#shoes.ItemQty
</td>
<td>
#shoes.ItemUnitPrice
</td>
<td>
#Html.ActionLink("View", "Details", "Shoes", new { id=shoes.Id}, new { #class = "view-Modal",#data_toggle="modal" ,#data_target="#myModal"})
</td>
</tr>
}
</table>
#*Open Modal Testing*#
#section scripts
{
<script src="~/Scripts/jquery.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#myModal').hide();
$("#btn_Modal").click(function () {
$('#myModal').modal('show');
});
$(".view-Modal").click(function () {
var productId =
$(this).closest('tr').find('#hiddenval').val();
$.ajax({
type: 'POST',
url: '/Shoes/Details',
data: { id: productId },
success: function (response)
{
$('#modalBody').html(response);
$('#myModal').modal('show');
}
});
})
$(".close").click(function ()
{
console.log("Clear All");
});
});
</script>
}
partial view: _details
#model ShoeInformation.Models.Shoes
<div>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Details</h4>
</div>
<div class="modal-body">
<table class="tablemodel">
<tr>
<tr>
#Html.DisplayFor(x=>x.Id)
</tr>
<tr>
#Html.DisplayFor(x=>x.ProductName)
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
I try to breakpoint to see the problem but everything is working properly, however in the modal it display the same value
can someone please help me regarding to this matter
thanks in advance

Send a string list to the controller using RouteValueDictionary

I have a search screen which gives the results in a paged list. On changing the page I need to get the values of the Model to the GET method in the controller. While I was able to pass the model properties which are strings, I am having an issue passing the string list.
View Code :
<div class="divSearch">
<div class="divCriteria">
<div class="row">
<div class="col-md-6">
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name, new { #class = "form-control" })
</div>
<div class="col-md-6">
#Html.LabelFor(m => m.Owner)
#Html.TextBoxFor(m => m.Owner, new { #class = "form-control" })
</div>
</div>
<br />
<div class="row">
<div class="col-md-6">
#Html.LabelFor(m => m.County)
#Html.ListBoxFor(model => model.County, Model.CountiesList, new { #class = "form-control", multiple = "multiple" })
</div>
</div>
<br />
<div class="row">
<div class="right">
<button type="submit" class="btn btn-primary"><i class="fa fa-share-square-o"></i>Search</button>
</div>
</div>
</div>
<div class="divResults">
<div class="table-responsive">
<table class="table table-hover table-advance dataTable">
<thead>
<tr>
<th style="display:none">ID</th>
<th>Name</th>
<th>Type</th>
<th>County</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.SearchList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
#Html.HiddenFor(modelItem => item.ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Type)
</td>
<td>
#Html.DisplayFor(modelItem => item.County)
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
#if (Model.SearchList != null)
{
var county = new List<string>();
foreach (var item in Model.County)
{
county.Add(item);
}
#Html.PagedListPager(Model.SearchList, Page => Url.Action("Index", "FacilityFinder", new RouteValueDictionary() { { "Page", Page }, { "name", Model.Name }, { "owner", Model.Owner }, { "county", county} }),PagedListRenderOptions.PageNumbersOnly)
}
Controller code :
public ActionResult Index(int? page=null,string name = null, List<string> county=null,string owner = null)
{
}
The value for name and owner are fine in the controller, but the list of county gives me System.Collections.Generic.List`1[System.String]
Am I missing something?
You can't pass complex types such as lists. You might need to construct your RouteValueDictionary dynamically:
var query = new RouteValueDictionary
{
{ "name", Model.Name },
{ "owner", Model.Owner }
};
for (var i = 0; i < Model.County.Count; i++)
{
query["county[" + i + "]"] = Model.County[i];
}
#Html.PagedListPager(
Model.SearchList,
Page => Url.Action("Index", "FacilityFinder", new RouteValueDictionary(query) { { "Page", Page } }),
PagedListRenderOptions.PageNumbersOnly
)
so that the resulting url looks like this:
/FacilityFinder/Index?Page=5&name=Foo&owner=Bar&county[0]=foo1&county[1]=foo2...
which will make the default model binder in ASP.NET MVC happy and properly bind this to a List<string>.

ASP .NET MVC RAZOR - Wrong Function Call

I have 2 seperate views and each of them call upon a controller that uploads a file. They both work okay the 1st time I use them, however for some unkown reason when i switch views the controllers from each view are swapped!! I double checked and i call each controller correctly. So i have no idea why the controllers are swapped between views!
Here is where I input the file:
<div class="options">
<input type="button" id="importexcel" name="importexcel" class="k-button" value="Select Excel File" />#*#T("Admin.Common.ImportFromExcel")" />*#
</div>
using(Html.BeginForm("GetFile", "Product", FormMethod.Post, new { EncType = "multipart/form-data" }))
{
<br />
}
<div id="importexcel-window" style="display:none;">
#using (Html.BeginForm("GetFile", "Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(x => x.Id)
<table style="text-align:left;">
<tr>
<td colspan="2">
<em>#T("Admin.Catalog.Products.List.ImportFromExcelTip")</em>
</td>
</tr>
<tr>
<td>
#T("Admin.Common.ExcelFile"):
</td>
<td>
<input type="file" id="importexcelfile" name="importexcelfile" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" class="k-button" value="#T("Admin.Common.ImportFromExcel")" />
</td>
</tr>
</table>
}
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#importexcel").click(function (e) {
e.preventDefault();
var window = $("#importexcel-window");
if (!window.data("kendoWindow")) {
window.kendoWindow({
modal: true,
width: "400px",
title: "#T("Admin.Common.ImportFromExcel")",
actions: ["Close"]
});
}
window.data('kendoWindow').center().open();
});
});
</script>
And here is the respective controller:
[HttpPost]
public ActionResult GetFile(int Id, HttpPostedFileBase importexcelfile)
{
/* read data from file */
var file = System.Web.HttpContext.Current.Request.Files[0];
FileChoosen = true;
FilePath = importexcelfile;
if (file.ContentLength > 0)
{
/* load and show data */
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Administration/Content/Excel/"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Edit", new { id = Id });
}
As mentioned above i have another input controller alike to this one in a different view with a different name: (notice its exactly alike the one on top but with a different name "GetXML" and "importXMLfile"
Here is the controller
[HttpPost]
public ActionResult GetXML(int Id, HttpPostedFileBase importXMLfile)
{}
And here is where i input it:
<div id="importexcel-window" style="display:none;">
#using (Html.BeginForm("GetXML", "Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(x => x.Id)
<table style="text-align:left;">
<tr>
<td>
#T("Admin.Common.ExcelFile"):
</td>
<td>
<input type="file" id="importXMLfile" name="importXMLfile" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" class="k-button" value="#T("Admin.Common.ImportFromExcel")" />
</td>
</tr>
</table>
}

Unable to pass list to controller with data table. ASP.net

I have a cshtml page that will be sending a list of items over to my controller. However when i click on the submit button, nothing is being passed over to my controller.
The codes below is my cshtml codes which will pass the model over to my controller.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-group">
#if (Model.Count() != 0)
{
<input type='button' value='Save and Update' class="btn btn-primary" data-toggle="modal" data-target="#myModal" />
}
</div>
<table class="table cell-border" id="TempTable5">
<tbody>
#if (Model.Count() != 0)
{
int j = 0;
foreach (var item in Model)
{
#Html.HiddenFor(model => item.ExerciseInstruction.ExerciseInstructionID)
<tr>
<td align="center">
<div class="form-group">
#Html.DisplayFor(model => item.ExerciseInstruction.ExerciseInstructionID)
</div>
</td>
<td>
<div class="form-group">
#Html.DisplayFor(model => item.Exercise.Name)
</div>
</td>
<td>
<div class="form-group">
<iframe width="300" height="175" src=#item.ExerciseVideo.VideoURL frameborder="0" allowfullscreen></iframe>
</div>
</td>
<td align="center">
#Html.DisplayFor(model => item.Therapist.Name)
</td>
<td>
#Html.DisplayFor(model => item.ExerciseInstruction.Prescribed_Date)
</td>
<td>
No. of Reps: #item.ExerciseInstruction.Number_Of_Reps<br />
No. of Secs to hold: #item.ExerciseInstruction.Number_Of_Secs_PositionHold<br />
No. of Sets: #item.ExerciseInstruction.Number_Of_Sets_Per_Day<br />
No. of Times: #item.ExerciseInstruction.Frequency_Per_Week<br />
Remarks: #if (item.ExerciseInstruction.Remark == null || item.ExerciseInstruction.Remark.Trim() == "")
{
#:NIL
}
else
{
#item.ExerciseInstruction.Remark
}
</td>
<td align="center">
#Html.EditorFor(model => item.ExerciseInstruction.ToPerform, new { htmlAttributes = new { style = "width:23px; height:23px;" } })
</td>
<td>
#Html.ActionLink("View", "Details", new { id = Model[j].ExerciseInstruction.ExerciseInstructionID, pageFrom = "performExercises" }, new { target = "_blank" })
</td>
</tr>
j++;
}
}
</tbody>
</table>
#if (Model.Count() != 0)
{
<input type='submit' value='Save and Update' class="btn btn-primary" data-toggle="modal" data-target="#myModal" />
}
}
The controller that is working on this is as below.
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Therapist")]
public ActionResult ToPerformExercises(int? pid, List<AssignmentViewModel> avmLIst)
{
if (ModelState.IsValid)
{
foreach (var item in avmLIst)
{
ExerciseInstruction eI = db.ExerciseInstructions.SingleOrDefault(a => a.ExerciseInstructionID == item.ExerciseInstruction.ExerciseInstructionID);
eI.ToPerform = item.ExerciseInstruction.ToPerform;
db.Entry(eI).State = EntityState.Modified;
db.SaveChanges();
}
}
return RedirectToAction("ViewToPerform", "AssignExercisesViewModel", new { pid = pid });
}
This is the submit pop up box
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!— Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to add/remove the Ongoing Exercise(s) for the patient?</p>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-primary" value="Confirm" onclick="DisableButton(this)" />
<button type="button" class="btn btn-default" data-dismiss="modal" id="cancel">Cancel</button>
</div>
</div>
</div>
</div>
My problem is very similar to this link Jquery tool DataTable unable to post/submit in an MVC3 Html.BeginForm
However i am unsure of how he actually solve it as the explanation on his answer was really brief.
Can anyone assist?
There's a lot going on here, but I'll take a shot at it based on a common pitfall in model binding... You should change the foreach to a for loop, then alter your HtmlEditorFor calls to use the index.
So to greatly simplify what you have above...
for(int i = 0; i < model.Count; i++)
{
// other things
#Html.EditorFor(model => model[i]. //rest of stuff
// more other things
MVC serializes a name into the element for you, then attempts to re-map this server-side when posting the form. If you use a foreach loop in this way, it will lose the index and fail to bind.
You can see this effect happening if you watch your requests in Fiddler (or Chrome or whatever).
Check out this answer. They experienced a similar problem when using foreach instead of for. The model binding does not work in the former case.
Model.List is null on POST using Razor

Mvc3 fill data after dropdownlist value changed

I have form which contains some text filed for filling data. I want to fill data in text box after dropdownlist changed.
MyView.chstml
#model BloodBank.Models.NewCamp
#{
ViewBag.Title = "New Camp";
Layout = "~/Views/Shared/_Layout - Menu.cshtml";
}
<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>
<script type="text/javascript">
$(function () {
$("select#OrganisationID").change(function (evt) {
if ($("select#OrganisationID").val() != "0") {
$.ajax({
url: "GetOrganizationInfo?orgID=" + $("select#OrganisationID").val(),
type: 'POST',
data: { OS: $("select#OrganisationID").val() },
success: function (response) {
$("select#OrganisationID").replaceWith(response)
},
error: function (xhr) {
alert("Something went wrong, please try again");
}
});
}
});
});
</script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true, "New Camp creation was unsuccessful. Please correct the errors and try again.")
<div>
<table style="border-style:none;border-width:0;border:0;">
<tbody>
<tr>
<td style="border:0;vertical-align:middle;">
<div class="editor-label">
#Html.LabelFor(m => m.OrganisationID)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.DropDownListFor(m => m.OrganisationID, (SelectList)ViewBag.OrganisationList)
#* <select id="Area">
#foreach (var arearow in (SelectList)ViewBag.OrganisationList)
{
<option value="#arearow.Value">#arearow.Text</option>
}
</select>*#
#Html.ActionLink("Add New Organisation", "AddOrganisation", "Organisation", null, null)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.ValidationMessageFor(m => m.OrganisationID)
</div>
</td>
</tr>
<tr>
<td style="border:0;text-align:left;" colspan="2"> <h3>Contact Person Information</h3></td>
</tr>
<tr>
<td style="border:0;">
<div class="editor-label">
#Html.LabelFor(m => m.Email)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.TextBoxFor(m => m.Email)
#Html.ValidationMessageFor(m => m.Email)
</div>
</td>
</tr>
<tr>
<td style="border:0;">
<div class="editor-label">
#Html.LabelFor(m => m.FirstName)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.TextBoxFor(m => m.FirstName)
#Html.ValidationMessageFor(m => m.FirstName)
</div>
</td>
</tr>
<tr>
<td style="border:0;">
<div class="editor-label">
#Html.LabelFor(m => m.LastName)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.TextBoxFor(m => m.LastName)
#Html.ValidationMessageFor(m => m.LastName)
</div>
</td>
</tr>
<tr>
<td style="border:0;">
<div class="editor-label">
#Html.LabelFor(m => m.Phone)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.TextBoxFor(m => m.Phone)
#Html.ValidationMessageFor(m => m.Phone)
</div>
</td>
</tr>
<tr>
<td colspan="2" style="border:0;text-align:center;">
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Submit" id="ClickMe" class="cssLoginButton blue"/>
</div>
}
My Action
[Authorize]
[OutputCache(Location = OutputCacheLocation.None)]
public ActionResult NewCamp()
{
var user = (BloodBank.Security.BloodBankMembershipUser)Membership.GetUser();
this.BindOrganisations(user.BloodBankID);
return View();
}
public ActionResult GetOrganizationInfo(string orgID)
{
if (!string.IsNullOrEmpty(orgID))
{
var model = (new UserManager()).GetCampPersonOrganisationDetailsByOrganisationID(orgID);
Models.NewCamp newcampModel = new Models.NewCamp();
if (model.Count > 0)
{
newcampModel.CampID = model[0].CampID;
newcampModel.Organisation = "";
newcampModel.OrganisationID = model[0].OrganisationID;
newcampModel.FirstName = model[0].FirstName;
newcampModel.LastName = model[0].LastName;
newcampModel.Email = model[0].Email;
newcampModel.Phone = model[0].Phone;
var organisations = this.GetOrganisations(model[0].BloodBankID);
if (organisations != null)
ViewBag.OrganisationList = new SelectList(organisations, "OrganisationID", "NameCity");
}
return View("NewCamp", newcampModel);
}
else
return View();
}
I am not able to fill data in the form. I am not getting why I am not able to fill data. Is there any change in script or in my code? Is there any example to fill data after dropdownlist value changed?
--------- Update------------
I have tried similar thing on a sample project. Here I can fetch the values and display in text box, but I get one more view added on same View every time I choose OS from dropdown as in below screenshot.
the only flaw in the code you posted might be a missing ;
success: function (response) {
$("select#OrganisationID").replaceWith(response);
},
Hello Everyone I have solved my problem using this. There is no need to create any javascript. I have solved this without using javascript.
#Html.DropDownListFor(m => m.OrganisationID, (SelectList)ViewBag.OrganisationList, new { onchange = "document.location.href = 'NewCamp?orgID=' + this.options[this.selectedIndex].value;" })

Categories

Resources