Get selected values from multiple selectlists in MVC3 controller - c#

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

Related

Render view in modal

I am trying to render a view in a modal but I can't figure out how to do this.
I tried a workaround by creating a partial view but could not trigger a method in the home controller (on load form).
I was wondering, is it possible to have a partial view triggering a method in the controller or should I changed it to a casual view (which I did not manage to show it)?
view:
#model IEnumerable<CharityProject.Models.UserInfos>
#{
ViewData["Title"] = "SelectAddress";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Select Address</h2>
<p>
#* <input type="button" value="Add New Address" onclick="location.href='#Url.Action("Create", "UserInfos")'" />*#
<input type="button" data-toggle="modal" data-target="#myModal" value="Add New Address" class="btn btn-default">
</p>
<div class="row">
<div class="col-md-6">
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Cities)
</th>
<th>
#Html.DisplayNameFor(model => model.Area)
</th>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<th>
#Html.DisplayNameFor(model => model.POB)
</th>
<th>
#Html.DisplayNameFor(model => model.PhoneNo)
</th>
<th>
#Html.DisplayNameFor(model => model.PhoneNo2)
</th>
<th>
#Html.DisplayNameFor(model => model.IsDefault)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Cities.CityName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Area)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.POB)
</td>
<td>
#Html.DisplayFor(modelItem => item.PhoneNo)
</td>
<td>
#Html.DisplayFor(modelItem => item.PhoneNo2)
</td>
<td>
#Html.DisplayFor(modelItem => item.IsDefault)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="col-md-6">
</div>
</div>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<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" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
**#{await Html.RenderPartialAsync("CreateAddress", new UserInfos());}**
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" uiactions="#Url.Action("Create", "UserInfos")" formmethod="post">Save changes</button>
</div>
</div>
</div>
</div>
Home controller:
public ActionResult CreateAddress()
{
return View();
}
I haven't used ,Net Core as of yet, still in the learning process, but from what I remember from the classic MVC approach(.NET),
Create a an AJAX method that will send data to the controller using
#Html.Action/#Html.ActionLink/#Url.Action, etc
The partial View should have access to the main view's Model object ( if you do a #Html.Partial)
If you are using ASP.NET Core you should use View Components.
Create a class deriving from ViewComponent containing the InvokeAsync method:
public class AddressViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
return View();
}
}
Put your view in this path structure "/Views/Shared/Components/Address/Default.cshtml".
Then, to render the component in your modal:
<div class="modal-body">
#await Component.InvokeAsync("Address")
</div>

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

Displaying a PartialView with updated data

C#, MVC4
I have a PartialView created for a popup data entry on a form. This is a snippet from the main form.
<input type="button" id="btnAddGroup" value="Add Group" />
<p>
<input type="submit" value="Save" />
</p>
</div>
</fieldset> }
I discovered quickly that I needed to have the line:
#Html.Partial("_Groups")
Outside the primary view so the form submit button in the partial view would accept and process.
My controller processes and sends back the data using:
return PartialView(NewModel);
I can run the debugger and see that the data is getting passed back to the PartialView but since the view sits outside the original form, it's not displaying.
My PartialView is as follows:
#model OMD.ViewModels.SearchedUser
#if (Model.AddGroups != null)
{
<h2>Groups to be Added</h2>
<table id="AddGroupList">
<thead>
<tr>
<th>
Name
</th>
<th>
Until
</th>
<th>
Action
</th>
</tr>
</thead>
<tbody>
#foreach (var Group in Model.AddGroups)
{
<tr>
<td>
#Html.DisplayFor(model=> Group.GroupName)
</td>
<td>
#Html.DisplayFor(model=> Group.dtAddedTo)
</td>
<td>
#Html.DisplayFor(model=> Group.bAddOrRemove)
</td>
<td>
#if (AuthCheck.CheckUser(new HttpContextWrapper(HttpContext.Current), oRoles.StaffChangeRequest) ||
AuthCheck.CheckUser(new HttpContextWrapper(HttpContext.Current), oRoles.StudentChangeRequest))
{
<span>#Html.ActionLink("Remove", "RemoveGroup", new { id = Group.ID })</span>
}
</td>
</tr>
}
</tbody>
</table>
}
<div id="dlgAddGroup" title="Add Group" style="display: none">
#using (Ajax.BeginForm("_Groups",new AjaxOptions { UpdateTargetId ="ID",OnSuccess="onSuccess"}))
{
#Html.DropDownListFor(model => model.AllGroups,new SelectList(Model.AllGroups, "ID","GroupName"), "Select Group to Add")
#Html.ValidationMessageFor(model => model.AllGroups)
<div class="editor-label">
#Html.CheckBox("cbxMakeGroupPermanent", true) Permanent
</div>
<div class="editor-label" id ="dlgUntil1">
Group Add Until:
</div>
<div class="editor-field" id="dlgUntil2">
#Html.TextBox("tbAddUntil",null,new { maxlength = 30, style = "width: 100px" })
<span style='padding:5px'><img id='calImageGroup' alt="img" src='~/Images/calendar.gif'></span>
</div>
<button class="btn btn-inverse" type="submit">add</button>
}
I can see the table at the top display the information posted back to it but it doesn't show on the screen...
How can I get this data/table to display?

Can't create any partial views in asp.net mvc 4?

I am getting this error when trying to load a partial view, and I don't know what the issue is:
System.InvalidOperationException: The model item passed into the
dictionary is of type 'CDB.OrderM', but this dictionary requires a
model item of type
'System.Collections.Generic.IEnumerable`1[CDB.tblItem]'.
public ActionResult Index()
{
OrderM om = new OrderM();
List<tblItem> tList = db.Query<tblItem>("Select * from tblItem").ToList<tblItem>();
ViewBag.tList = tList;
return View(om);
}
public ActionResult Reqitem()
{
//tblItem ti= db.Query<tblItem>("select * from tblItem");
var ti = db.Query<tblItem>("select * from tblItem");
return PartialView("_rawmat",ti);
}
My Partial View codes are-
#model IEnumerable<CDB.tblItem>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.ItemId)
</th>
<th>
#Html.DisplayNameFor(model => model.ItemName)
</th>
<th>
#Html.DisplayNameFor(model => model.MeasuringUnit)
</th>
<th>
#Html.DisplayNameFor(model => model.Rate)
</th>
<th>
#Html.DisplayNameFor(model => model.Quantity)
</th>
<th>
#Html.DisplayNameFor(model => model.BagSz)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ItemId)
</td>
<td>
#Html.DisplayFor(modelItem => item.ItemName)
</td>
<td>
#Html.DisplayFor(modelItem => item.MeasuringUnit)
</td>
<td>
#Html.DisplayFor(modelItem => item.Rate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Quantity)
</td>
<td>
#Html.DisplayFor(modelItem => item.BagSz)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
and Index view codes are...
#model CDB.OrderM
#{
ViewBag.Title = "Index";
var tList = ViewBag.tList;
}
<h2>Index</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>OrderM</legend>
<div class="editor-label">
#Html.LabelFor(model => model.OdrId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OdrId)
#Html.ValidationMessageFor(model => model.OdrId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OrderNo)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OrderNo)
#Html.ValidationMessageFor(model => model.OrderNo)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OdrDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OdrDate)
#Html.ValidationMessageFor(model => model.OdrDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OdrQty)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OdrQty)
#Html.ValidationMessageFor(model => model.OdrQty)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OdrAmount)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OdrAmount)
#Html.ValidationMessageFor(model => model.OdrAmount)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.DDate)
#Html.ValidationMessageFor(model => model.DDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CId)
#Html.ValidationMessageFor(model => model.CId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Pod)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Pod)
#Html.ValidationMessageFor(model => model.Pod)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
#Html.Partial("_rawmat")
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
It looks like what you want to do is change #Html.Partial("_rawmat") to #Html.Action("Reqitem"). This is because your original statement says go straight to the view and since you haven't passed a model it will pass the same model as the view that it is included on.
So if you use #Html.Partial("_rawmat") on your index view it will pass the model that it has which is of type OrderM and not actually call the action you have written at all.
I dont know why you people are missing out the available syntax to call a partial view with a model
{#Html.RenderPartial("_PartialView",List<CDB.tblItem>) }
Where I assume the partial view uses the Model of type List<CDB.tblItem>.
If you want to populate the model with any values. just before the above syntax use
#{
//code to populate your model
}
If your partial view is expecting a List, then change the method like this...
public ActionResult Reqitem()
{
//tblItem ti= db.Query<tblItem>("select * from tblItem");
var ti = db.Query<tblItem>("select * from tblItem").ToList();//notice to List
return PartialView("_rawmat",ti);
}
I have added .ToList() to the end of the query.
I think the issue is in the second call of #Html.Partial("_rawmat") inside your Index.
It does not pass a model parameter, so it passed the default one, which is a CDB.OrderM.
Use this instead (it renders the action instead of the partial view):
#Html.Action("Reqitem")

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