Mvc3 fill data after dropdownlist value changed - c#

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;" })

Related

Add child to parent list inside MVC parent edit

I have an edit page for a ComicPanel which contains a list of ComicPanelText.
I want to add a new ComicPanelText, so I need an 'Add' button, but the submit button goes to my EditController. How can I add a new submit button determine which button was pressed in the controller?
Views/Shared/EditorTemplates/ComicPanelText.cshtml
#model ComicNet.Models.ComicPanelText
<tr>
<td></td>
<td>
#Html.HiddenFor(x => x.ComicPanelTextId)
#Html.TextBoxFor(x => x.ComicText)
</td>
</tr>
Views/ComicPanels/Edit.cshtml
#model ComicNet.Models.ComicPanel
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<form action="" method="post" enctype="multipart/form-data">
#Html.AntiForgeryToken()
#Html.ValidationSummary(true);
<table>
<tr>
<td>
#Html.LabelFor(m => m.Name)
</td>
<td>
#Html.EditorFor(m => m.Name)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.PanelNumber)
</td>
<td>
#Html.EditorFor(m => m.PanelNumber)
</td>
</tr>
<tr>
<td></td>
<td>
<img src='#Html.DisplayFor(model => model.Url)' width="200" height="200" />
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Width)
</td>
<td>
#Html.EditorFor(m => m.Width)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Height)
</td>
<td>
#Html.EditorFor(m => m.Height)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.ImageUpload)
</td>
<td>
#Html.TextBoxFor(m => m.ImageUpload, new { type = "file" })
</td>
</tr>
#Html.EditorFor(x => x.ComicPanelTexts)
</table>
<div>
#Html.HiddenFor(m => m.FileName)
</div>
<div>
#Html.HiddenFor(m => m.ComicPanelId)
</div>
<button type="submit">Update</button>
</form>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
ComicPanelsController.cs
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ComicPanel comicPanel)
{
//...
}
I guess you can pass the button name into the Controller
<input name="submit" type="submit" id="addText" value="Add" />
public ActionResult Edit(ComicPanel comicPanel, string submit)
{
if(submit == "Add")
{
var newComicPanelText = new ComicPanelText();
comicPanel.ComicPanelTexts.Add(newComicPanelText);
db.Entry(newComicPanelText).State = EntityState.Added;
db.Entry(comicPanel).State = EntityState.Modified;
db.SaveChanges();
return View(comicPanel);
}

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>.

How to get checkbox value in mvc?

when i will select check box and will be clicked select button how i can get this value to the textbox value. Here checkbox id= chk and textbox id = OrderNo. Please help me ....I have something in below....
$("#OrderNo").blur(function() {
$.get('/Ordering/OrderList/', function(data) {
$('#orlist').html(data);
});
$('#orlist').dialog({
width: 500,
height: 350,
open: true,
title: 'Select Order',
buttons: {
Select: function() {
if (("#chk") == 'checked') {
var por = ("#porderno").val();
por = ("#OrderNo");
}
},
Cancel: function() {
$('#orlist').dialog('close');
$('#orlist').empty();
}
}
});
Partial view page is
#model IEnumerable<testcon.OrderM>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.OdrId)
</th>
<th>
#Html.DisplayNameFor(model => model.OrderNo)
</th>
<th>
#Html.DisplayNameFor(model => model.CId)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.CheckBox("OdrId", new { #id="chk"})
</td>
<td class="left">
#Html.DisplayFor(modelItem => item.OrderNo, new { #id="porderno"})
</td>
<td class="left">
#Html.DisplayFor(modelItem => item.CId)
</td>
</tr>
}
</table>
And My Create View page is
#model testcon.DeliveryInfo
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>DeliveryInfo</legend>
#*<div class="editor-label">
#Html.LabelFor(model => model.DId)
</div>*#
<div class="editor-field">
Delivery Id : #Html.EditorFor(model => model.DId)
#Html.ValidationMessageFor(model => model.DId)
</div>
#*<div class="editor-label">
#Html.LabelFor(model => model.OrderNo)
</div>*#
<div class="editor-field">
Order No :#Html.EditorFor(model => model.OrderNo)
#Html.ValidationMessageFor(model => model.OrderNo)
#*Show Order*#
</div>
#* <div class="editor-label">
#Html.LabelFor(model => model.DDate)
</div>*#
<div class="editor-field">
Delivery Date : #Html.EditorFor(model => model.DDate)
#Html.ValidationMessageFor(model => model.DDate)
</div>
#*<div class="editor-label">
#Html.LabelFor(model => model.DQuantity)
</div>*#
<div class="editor-field">
Delivery Quantity: #Html.EditorFor(model => model.DQuantity)
#Html.ValidationMessageFor(model => model.DQuantity)
</div>
#*<div class="editor-label">
#Html.LabelFor(model => model.DAmount)
</div>*#
<div class="editor-field">
Delivery Amount : #Html.EditorFor(model => model.DAmount)
#Html.ValidationMessageFor(model => model.DAmount)
</div>
<div id="orlist" >
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Use .is(':checked') check if checked...
buttons: {
Select: function() {
if ($("#chk").is(':checked')) {
$("#OrderNo").val($("#porderno").val());
}
},
to check if the check box is checked in jQuery, you can do it by either
//will return true if the check box is checked otherwise false!
$("#chkBoxId").is(':checked');
or
this approach is good when dealing with group of radio buttons/checkboxes.
//will yield the same result if checkbox is checked
$('input[name="chkBoxName"]:checked').val();
So you can use them in your code like what #Anthony Chu has responded which i was about to write :)

Get selected values from multiple selectlists in MVC3 controller

There is a view displaying 5 dropdown lists populated with all available courses from relevant table:
#model StudentRegistrationPortal.Models.CourseRegisterModel
#{
ViewBag.Title = "registerCourses";
}
<h2>Welcome
#Context.User.Identity.Name
</h2>
#Html.ActionLink("[Sign Out]", "SignOut", "Admin")
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Following are available Courses - Please select Courses to Register</legend>
<table>
<tr>
<td>
<div class="editor-label">
Course-1:
</div>
</td>
<td>
<div class="editor-field">
#Html.DropDownListFor(m => m.Course.CId, Model.CoursesList)
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-label">
Course-2:
</div>
</td>
<td>
<div class="editor-field">
#Html.DropDownListFor(m => m.Course.CId, Model.CoursesList)
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-label">
Course-3:
</div>
</td>
<td>
<div class="editor-field">
#Html.DropDownListFor(m => m.Course.CId, Model.CoursesList)
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-label">
Course-4:
</div>
</td>
<td>
<div class="editor-field">
#Html.DropDownListFor(m => m.Course.CId, Model.CoursesList)
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-label">
Course-5:
</div>
</td>
<td>
<div class="editor-field">
#Html.DropDownListFor(m => m.Course.CId, Model.CoursesList)
</div>
</td>
</tr>
</table>
<p>
<input type="submit" value="Register" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Home","Student")
</div>
Student will select one course from each dropdown lists and press Register button.
My question is how I will get selected courses in relevant controller?
Thanks.
What you should really do is in your model have properties SelectedCourse1, SelectedCourse2 etc., populate them accordingly and send the model back to the controller

Button click event does nothing

View
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<fieldset>
<br />
<br />
<br />
<div align="center">
#{
#(Html.Telerik().Grid<SmartTrack.Web.DAL.SysUserList>()
.DataBinding(dataBinding => dataBinding.Ajax().Select("Index", "User"))
.Name("UserList")
.DataKeys(keys => keys
.Add(c => c.UserName)
.RouteKey("UserName"))
.Columns(columns =>
{
columns.Bound(o => o.UserName).Width(100);
columns.Bound(o => o.FirstName).Width(200);
columns.Bound(o => o.LastName).Width(250);
columns.Bound(o => o.Active).ClientTemplate("<input type='checkbox' disabled='disabled' name='Active' <#=Active? checked='checked' : '' #> />").Width(70).HtmlAttributes(new { style = "text-align:center" }); ;
})
.Pageable(pagerAction => pagerAction.PageSize(20))
.Sortable()
.Selectable()
.Scrollable()
.Groupable()
.Filterable()
.HtmlAttributes(new { style = "width:50%;" })
)
}
</div>
<br/>
<div align="center">
<table>
<tr>
<td>
<button id="btnAdd" type="submit" style="height:40px;width:70px" ">Add</button>
</td>
<td>
<button style="height:40px;width:70px" ">Edit</button>
</td>
<td>
<button style="height:40px;width:70px" ">Delete</button>
</td>
</tr>
</table>
</div>
</fieldset>
<script type="text/javascript">
$(function () {
$('#btnAdd').click(function () {
$.ajax({
type: "POST",
url: '#Url.Action("Create","User")',
success: function (result) {
$('#cuscreate').html(result)
}
});
});
});
</script>
This view contain a script from which the UserController Create method is call when the add button is clicked
Control
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SmartTrack.Web.Attributes;
using SmartTrack.Web.Models;
using SmartTrack.Web.DAL;
using Telerik.Web.Mvc;
namespace SmartTrack.Web.Controllers
{
public class UserController : Controller
{
SMARTTrackerEntities db = new SMARTTrackerEntities();
//
// GET: /User/
[GridAction]
public ActionResult Index()
{
//ViewData["UserGroup"] = DisplayContentEngine.getUserGroupList();
return View(new GridModel(UserListEngine.getAllSystemUser()));
}
[HttpPost]
public ActionResult Create()
{
ViewData["Location"] = DisplayContentEngine.getLocationList();
ViewData["Branch"] = DisplayContentEngine.getBranchList();
//var v = ViewData.Model = UserListEngine.getAllSystemUser();
var user = new SysUserList();
return View(user);
}
[HttpPost]
public ActionResult Create(SysUserList user)
{
try
{
// TODO: Add insert logic here
if (ModelState.IsValid)
{
//Save Registration
db.SysUserLists.AddObject(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
catch
{
return View();
}
}
public ActionResult Edit(string username)
{
SysUserList sysuserlist = db.SysUserLists.Single(s => s.UserName == username);
return View(sysuserlist);
}
}
}
This controller that is called
Create View
#model SmartTrack.Web.DAL.SysUserList
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
<div id="cuscreate">
<fieldset>
<table>
<tr>
<td>
<label>First Name</label>
</td>
<td>
#Html.TextBoxFor(model => model.FirstName)
</td>
<td>
<label>Last Name</label>
</td>
<td>
#Html.TextBoxFor(model => model.LastName)
</td>
</tr>
<tr>
<td>
<label>User Name</label>
</td>
<td>
#Html.TextBoxFor(model => model.UserName)
</td>
<td>
<label>Password</label>
</td>
<td>
#Html.PasswordFor(model => model.userPwd)
</td>
</tr>
<tr></tr>
<tr>
<td>
<label>Location</label>
</td>
<td>
#(Html.Telerik().DropDownList()
.Name("ddLocation")
.BindTo((IEnumerable<DropDownItem>)ViewData["Location"])
.CascadeTo("ddlBranch")
)
</td>
<td>
<label>Branch</label>
</td>
<td>
#(Html.Telerik().DropDownList()
.Name("ddlBranch")
.BindTo((IEnumerable<DropDownItem>)ViewData["Branch"])
)
</td>
</tr>
</table>
</fieldset>
</div>
}
When the add button is click nothing happen can someone tell my whats my issue?
Thanks in advance
Regards
Kurt
I cannot see the form tags in your html that could be the reason where it does not know where to post
The view with action link Create New and the telerik grid does not have form tags in it
Make sure you cancel the default action of the submit button by returning false from your click handler in order to give your AJAX call chance to execute:
<script type="text/javascript">
$(function () {
$('#btnAdd').click(function () {
$.ajax({
type: "POST",
url: '#Url.Action("Create", "User")',
success: function (result) {
$('#cuscreate').html(result)
}
});
});
return false; // <!-- That's the important bit
});
</script>
You don't have a data element in your ajax request, so you are POSTing nothing.
If you want to get the data from the form you can just use .serialize():
$.ajax({
type: "POST",
data: $('form').serialize(),
url: '#Url.Action("Create","User")',
success: function (result) {
$('#cuscreate').html(result)
}
});
Keep in mind, this will only work if its the only on the page, otherwise you should use another selector, but you get the idea.
UPDATE from HatSoft's answer (upvote it!):
generally inside your tags you should have tags, to do that in MVC:
<fieldset>
#using(Html.BeginForm())
{
<p>your form</p>
}
</fieldset>
In correcting my problem I had to modify my index view to include div id = cuscreate which resulted in the CreateUser view displaying
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<div id="cuscreate" align="center">
<fieldset>
<br />
<br />
<br />
#using (Html.BeginForm())
{
//#{
#(Html.Telerik().Grid<SmartTrack.Web.DAL.SysUserList>()
.DataBinding(dataBinding => dataBinding.Ajax().Select("Index", "User"))
.Name("UserList")
.DataKeys(keys => keys
.Add(c => c.UserName)
.RouteKey("UserName"))
.Columns(columns =>
{
columns.Bound(o => o.UserName).Width(100);
columns.Bound(o => o.FirstName).Width(200);
columns.Bound(o => o.LastName).Width(250);
columns.Bound(o => o.Active).ClientTemplate("<input type='checkbox' disabled='disabled' name='Active' <#=Active? checked='checked' : '' #> />").Width(70).HtmlAttributes(new { style = "text-align:center" }); ;
})
.Pageable(pagerAction => pagerAction.PageSize(20))
.Sortable()
.Selectable()
.Scrollable()
.Groupable()
.Filterable()
.HtmlAttributes(new { style = "width:50%;" })
)}
</fieldset>
<br/>
<div align="center">
<table>
<tr>
<td>
<button id="btnAdd" type="submit" style="height:40px;width:70px" ">Add</button>
</td>
<td>
<button style="height:40px;width:70px" ">Edit</button>
</td>
<td>
<button style="height:40px;width:70px" ">Delete</button>
</td>
</tr>
</table>
</div>
</div>
<script type="text/javascript">
$(function () {
$('#btnAdd').click(function () {
$.ajax({
type: "POST",
data: $('form').serialize(),
url: '#Url.Action("CreateUser", "User")',
success: function (result) {
$('#cuscreate').html(result)
}
});
});
return false; // <!-- That's the important bit
});
</script>
Thanks for your assistance was really appreciated
Regards
Kurt

Categories

Resources