Add child to parent list inside MVC parent edit - c#

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

Related

Add Button Value into all Text Box in a For Loop

I have a quick question. I have a form with a for loop. Each for loop has a text box. I want to have two buttons that when I click on one, all the text boxes get populated with the value in the button. For example, when I click on the button "Add 50 minutes," I want all my text boxes to populate with 50. The same goes for if I click on the button "Add 110 minutes" (Screen shot attached)
Here is my form
#using (Html.BeginForm("Index", "Minutes", FormMethod.Post, new { enctype = "multipart/form-date", onsubmit = "popup()" }))
{
#Html.ValidationSummary(true)
<fieldset>
<div>
<table id="tablereport" class="table table-striped table-bordered table-hover table-condensed">
<thead style="background-color:black; font-weight:bold; color:aliceblue">
<tr>
</thead>
<tr>
<td><b>#Html.Label("Date :")</b></td>
<td>#Html.TextBox("datepicker", DateTime.Now.ToString("MM/dd/yyyy"), new { required = "required" })</td>
</tr>
<tr>
<td><input type="button" id="btnSetText" value="Add 50 Minutes" class="btn btn-default" onclick="setText" /></td>
<td><input type="button" value="Add 110 Minutes" class="btn btn-default" /></td>
</tr>
</table>
</div>
#if (ViewBag.Message != null)
{
<div id="dialog-message" title="Alert !!">
<p>
<span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>
#ViewBag.Message
</p>
</div>
}
<table id="tablereport" class="table table-striped table-bordered table-hover table-condensed">
<thead style="background-color:black; font-weight:bold; color:aliceblue">
<tr>
</thead>
<tr>
<th>Class ID</th>
<th>Course Title</th>
<th>Department</th>
<th>SID</th>
<th>Full Name</th>
<th>Minutes</th>
</tr>
#for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(model => model[i].ClassID)
#Html.HiddenFor(model => model[i].ClassID)
</td>
<td>
#Html.DisplayFor(model => model[i].CourseTitle)
#Html.HiddenFor(model => model[i].CourseTitle)
</td>
<td>
#Html.DisplayFor(model => model[i].Department)
#Html.HiddenFor(model => model[i].Department)
</td>
<td>
#Html.DisplayFor(model => model[i].SID)
#Html.HiddenFor(model => model[i].SID)
</td>
<td>
#Html.DisplayFor(model => model[i].FullName)
#Html.HiddenFor(model => model[i].FullName)
</td>
<td>
#Html.TextBoxFor(model => model[i].Minutes, new { #Value = "0" })
#Html.ValidationMessageFor(model => model[i].Minutes)
</td>
</tr>
}
</table>
<table align="center">
<tr>
<td><input type="submit" value="Save" class="btn btn-default" onclick="popup()" /></td>
</tr>
</table>
</fieldset>
}
Here is my script
<script>
var date = new Date();
var maxdate = date.getDate();
//var currentDate = $(".selector").datepicker("getDate");
$(function () {
$("#datepicker").datepicker({
defaultDate: maxdate,
minDate: '-1M',
maxDate: '+0D'
});
});
**function setText(){
var setText = document.getElementById('setText');
setText.value = '50';
}**
The script I have is working, but will only populate one text box.
Thank you!!
Well the ids should be unique for every element in the DOM. Even though in your case there's more than one element with the same id the document.getElementById() function returns one element(the first one with that id). What you want to do is add a class to each textbox and then use document.getElementsByClassName() which will return a list of all the elements that have the class.
For example:
$("#add-50").on('click', function() {
// ill intentionally use vanilla js here
var inputs = document.getElementsByClassName('textbox');
for (var i = 0; i < inputs.length; i++) {
var input1 = inputs[i];
input1.value = '50';
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button id="add-50">Click Me for 50</button><br/>
<input class="textbox" type="text" /><br/>
<input class="textbox" type="text" /><br/>
<input class="textbox" type="text" /><br/>
<input class="textbox" type="text" /><br/>
<input class="textbox" type="text" />
</div>
You can wrap all the textboxes in a div, add a class to all of them and then use something like this:
function setValue(value){
$('#divWithtextboxes .TextboxClass').each(function (i) {
$(this).val(value);
<br>
});<br>

asp.net mvc pass parameters between view and controller

I am a novice in asp.net and i want create simple database application.
I need pass parameters between view and controller to retrieve data from database.
i need only this data which title is "something". I create simple left menu which contains search settings.
This is my view page.
#model IEnumerable<TwojaBiblioteka.Models.Ksiazka>
#{
ViewBag.Title = "Home Page";
}
#Styles.Render("~/Content/css")
<div class="jumbotron">
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-2">
<h2>Szukaj</h2>
<div class="textboxes">
<input type="text" name="Tytul" class="form-control" id="Tytul" placeholder="Tytuł..." />
<input type="text" name="txtAutor" class="form-control" id="txtAutor" placeholder="Autor..." />
<input type="text" name="txtISBN" class="form-control" id="txtISBN" placeholder="ISBN..." />
</div>
<center>
#Ajax.ActionLink("Szukaj", "SzukajKsiazki", new AjaxOptions()
{
HttpMethod="GET",
UpdateTargetId= "divKsiazki",
InsertionMode= InsertionMode.Replace
})
</center>
</div>
<div id="divKsiazki"class="col-md-10 ">
</div>
</div>
</div>
</div>
This is view for display data from database:
#model IEnumerable<TwojaBiblioteka.Models.Ksiazka>
<table class="table" style="border:1px solid black;">
<tr>
<th>
#Html.DisplayNameFor(model => model.Tytul)
</th>
<th>
#Html.DisplayNameFor(model => model.Autor)
</th>
<th>
#Html.DisplayNameFor(model => model.ISBN)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Tytul)
</td>
<td>
#Html.DisplayFor(modelItem => item.Autor)
</td>
<td>
#Html.DisplayFor(modelItem => item.ISBN)
</td>
</tr>
}
</table>
And this is my controller:
public PartialViewResult SzukajKsiazki()
{
string tytul="something";
var ksiazkilist = db.Ksiazka.Where(x => x.Tytul == tytul).ToList();
return PartialView("_ListaKsiazek",wypozyczone);
}
So how i can pass data from my textboxes to controller to display only those records which contains textbox text?
Your controller action should accept a parameter. In Asp.Net MVC, it is normal for this to be the model:
public PartialViewResult SzukajKsiazki(IEnumerable<TwojaBiblioteka.Models.Ksiazka> model)
Your view should have all of the editor elements from the model enclosed in a form and you need a submit button:
#using (Html.BeginForm("SzukajKsiazki", "ControllerName", FormMethod.Post)
{
<table class="table" style="border:1px solid black;">
<tr>
<th>
#Html.DisplayNameFor(model => model.Tytul)
</th>
<th>
#Html.DisplayNameFor(model => model.Autor)
</th>
<th>
#Html.DisplayNameFor(model => model.ISBN)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Tytul)
</td>
<td>
#Html.DisplayFor(modelItem => item.Autor)
</td>
<td>
#Html.DisplayFor(modelItem => item.ISBN)
</td>
</tr>
}
</table>
<input type="submit" value="submit">
}

MVC: Passing Value from View to Controller

I am trying to pass values from a view to a controller in MVC. I am using a ViewModel and normally the values would bind to the properties as long as the names are the same. However because the values are generated via a foreach loop the names of the values do not match the names of the properties in the view model.
I am working around this by assigning the values to a variable in Razor. However one of my values is in a text box on the form and the value is not being passed to the controller and I cannot work out why.
I get a null exception when clicking the button.
VIEW Code is below:
#model PagedList.IPagedList<Mojito.Domain.ViewModels.ShoppingCartProductItem>
#using System.Web.UI.WebControls
#using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Mojito Products</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstOrDefault().Description)
</th>
<th>
#Html.ActionLink("Price", "Index", new { sortOrder = ViewBag.SortByPrice, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
#Html.DisplayNameFor(model => model.FirstOrDefault().Quantity)
</th>
<th>
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.TextBoxFor(modelItem => item.Quantity)
</td>
<td>
#{string Description = item.Description;}
#{decimal Price = item.Price;}
#{int Quantity = item.Quantity; }
#using (Html.BeginForm("AddToCart", "ShoppingCart", FormMethod.Post))
{
<div class="pull-right">
#if (Request.Url != null)
{
<input type="text" hidden="true" name="Description" value=#Description />
<input type="text" hidden="true" name="Price" value=#Price />
<input type="text" hidden="true" name="Quantity" value=#Quantity />
#Html.Hidden("returnUrl", Request.Url.PathAndQuery)
<input type="submit" class="btn btn-success" value="Add to cart" />
}
</div>
}
</td>
</tr>
}
</table>
<div class="col-md-12">
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
</div>
#Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
Controller Code below
public ActionResult AddToCart(Cart cart, MojitoProduct product, string returnUrl, int Quantity =1)
{
if (product != null)
{
cart.AddItem(product, Quantity);
}
return RedirectToAction("Index", new { returnUrl });
}
Do not use foreach. Use a for-loop instead and within this, qualify the full path to your properties using the index.
Better yet: use a Edit- or DisplayTemplate for the ShoppingCartProductItem. This will also keep your path.
You have to use for loop instead of foreach:
#for (int i=0;i < Model.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(modelItem => Model[i].Description)
</td>
<td>
#Html.DisplayFor(modelItem => Model[i].Price)
</td>
<td>
#Html.TextBoxFor(modelItem => Model[i].Quantity)
</td>
..........................
..........................
..........................
}
you can also post all using one form by posting List<ShoppingCartProductItem>, see Model Binding To A List
Your textboxes so values out of the form.
Try like below
#using (Html.BeginForm("AddToCart", "ShoppingCart", FormMethod.Post))
{
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.TextBoxFor(modelItem => item.Quantity)
</td>
<td>
#{string Description = item.Description;}
#{decimal Price = item.Price;}
#{int Quantity = item.Quantity; }
<div class="pull-right">
#if (Request.Url != null)
{
<input type="text" hidden="true" name="Description" value=#Description />
<input type="text" hidden="true" name="Price" value=#Price />
<input type="text" hidden="true" name="Quantity" value=#Quantity />
#Html.Hidden("returnUrl", Request.Url.PathAndQuery)
<input type="submit" class="btn btn-success" value="Add to cart" />
}
</div>
</td>
</tr>
}
}
I resolved this in the short term by using new and forcing the name of the parameter.
#Html.HiddenFor(modelItem => t.NoOfUsers, new { Name = "NoOfUsers", id = "NoOfUsers" })

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

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