Data from view to different controller - asp.net-mvc

2 Points
3 Posts
Data from view to different controller
1 minute ago|LINK
Hello friends
I'm from Colombia, sorry for the writing
I have a problem I do not know how to connect two controllers from one view, I'm using EF Data Base First, this automatic genre classes to my model, one of these classes is called "UNIVERSITY" which is a table of the database where are all the universities, and another class is "CAMPUS_UNIVERSITY" where are all the campus of a university, a university can have multiple campus
I have 2 controllers and their associated views
The first controller is "University" (I think i not necessary show) and your view "Index" (list all Universidadades). That is this:
#model IEnumerable<RolesMVC3.Models.UNIVERSITY>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
Nombre
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.ActionLink("Add Campus", "Create", "CampusUniversity" new { id=item.IdUniversity }) |
#Html.ActionLink("Edit", "Edit", new { id=item.IdUniversity }) |
#Html.ActionLink("Delete", "Delete", new { id=item.IdUniversity })
</td>
</tr>
}
</table>
The link "Add Campus" routed to controller "CampusUniversity" to the action "Create". That is this:
public ActionResult Create()
{
ViewBag.IdCityCampus = new SelectList(db.CITY_CAMPUS, "IdCityCampus", "Name");
ViewBag.IdUniversity = new SelectList(db.UNIVERSITY, "IdUniversity", "Name");
return View();
}
//
//
[HttpPost]
public ActionResult Create(CAMPUS_UNIVERSITY campus_university)
{
if (ModelState.IsValid)
{
db.CAMPUS_UNIVERSITY.AddObject(campus_university);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.IdCityCampus = new SelectList(db.CIUDAD_SEDE, "IdCityCampus", "Nombre", campus_university.IdCityCampus);
ViewBag.IdUniversity = new SelectList(db.UNIVERSIDAD, "IdUniversity", "Nombre", campus_university.IdUniversity);
return View(campus_university);
}
And the associated view (View "Create" Controller " CampusUniversity ") is:
#model RolesMVC3.Models.CAMPUS_UNIVERSITY
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<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>SEDE_UNIVERSIDAD</legend>
<div class="editor-label">
#Html.LabelFor(model => model.IdUniversity, "UNIVERSIDAD")
</div>
<div class="editor-field">
#Html.DropDownList("IdUniversity", String.Empty)
#Html.ValidationMessageFor(model => model.IdUniversity)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.IdCityCampus, "CITY_CAMPUS")
</div>
<div class="editor-field">
#Html.DropDownList("IdCityCampus", String.Empty)
#Html.ValidationMessageFor(model => model.IdCityCampus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AddressCampus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AddressCampuse)
#Html.ValidationMessageFor(model => model.AddressCampus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PhoneCampus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PhoneCampus)
#Html.ValidationMessageFor(model => model.PhoneCampus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MailCampus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MailCampus)
#Html.ValidationMessageFor(model => model.MailCampus)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
I want to do that by clicking "Add Campus" appears the name of the university comes fromthe table or class "UNIVERSITY" in the view Create (controller "SedeUniversidad") and that can save the campus of the university and not as I have now, because I have to choose the university of a DropDownList, how I can do?
Thank you, blessings!

I can't understand some of your English. It sounds like you want to send data from your Create view to your University controller. You can make the POST url of your form go wherever you want by putting the following values in your HTML.BeginForm statement in your Create view.
#using (Html.BeginForm("ActionName", "ControllerName"))

Related

using viewmodel with create view

I have a ViewModel with two models in it which works find when displaying data. My problem is I want to add a foreach() within the Create.cshtml file. Any ideas?
----Create.cshml-----
#model demo.Models.ViewModel
#{ ViewBag.Title = "Create Reference";}<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Submission Form </legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-field">
<!-- iterate through ExternalContentModel and make checkboxes. -->
#foreach (var item in Model.ExternalContentModel)
{
<label class="checkbox">
<input type="checkbox" name="users" value="#item.auth_lname"> #item.auth_lname
</label>
}
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OrganizationName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OrganizationName)
#Html.ValidationMessageFor(model => model.OrganizationName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Address)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Address)
#Html.ValidationMessageFor(model => model.Address)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.City)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
------Controller-----
//
// GET: /Create
public ActionResult Create() <=== can this be the problem????
{
demo.Models.ViewModel vm = new demo.Models.ViewModel();
vm.ExternalContentModel = _repository.ExternalContent();
// Return the content from the External Model to the Create.
return View(vm);
}
//
// POST: /MailingReferences/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Reference reference) <=== can this be the problem????
{
if (ModelState.IsValid)
{
db.References.Add(reference);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(reference);
}
If you have different models then why don't you just create a editor templates for each model?
You can do this by creating a folder called "EditorTemplates" in the same folder your Create.cshtml view lives in. Now add a view for your model into that folder. The view should be named the same as your model class. E.g. a class called FooBarModel would have an editor template called FooBarModel.cshtml.
You would then just use the editor template by doing #Html.EditorFor(x => x.FooBar)

ASP.NET MVC 4 Model property value lost coming back from Edit view

I have a model with a DateCreated value that is not scaffolded. Coming to GET Edit controller action I see that the model has a correct value that is passed on to the Edit view. Coming back from the view, POST method, the value for DateCreated is DateTime default. It's lost.
Does anyone know why? Controller and View are scaffolded.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Product product)
{
try
{
if (ModelState.IsValid)
{
product.DateEdited = DateTime.Now;
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException dex)
{
Console.Write(dex.Message);
ModelState.AddModelError("", reg6.Resources.UnableToSaveChanges);
}
return View(product);
}
#model reg6.Models.Product
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Product</legend>
<table>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
</td>
<td>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
<div>
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
</td>
<tr>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
</td>
<td>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
<div>
#Html.ValidationMessageFor(model => model.Description)
</div>
</div>
</td>
<tr>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.BasePrice)
</div>
</td>
<td>
<div class="editor-field">
#Html.EditorFor(model => model.BasePrice)
<div>
#Html.ValidationMessageFor(model => model.BasePrice)
</div>
</div>
</td>
<tr>
<tr>
<td>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</td>
<td align="right">
<input type="submit" value="Create" id='CreateButton' />
<td>
</tr>
</table>
</fieldset>
}
In your view place a hidden element for the DateCreated
#Html.HiddenFor(m=>m.DateCreated)
All the hidden elements will be posted to the server.

asp net mvc partial view validation

Hi how are you? I'm trying to validate a form in ASP NET MVC.
I have a partial view "Address" that I reuse for some entities, like Company, Person, etc.
My problem is that when I submit the form, only the controls of the father view gets validated, the ones in the partial view don't.
Here's some code I hope u can geive me hand
PERSON VIEW
#model Entities.Person
#using (Html.BeginForm("Create", "Person", FormMethod.Post))
{
<table>
<tr>
<td>
#Html.LabelFor(model => model.FirstName)
<div class="control">
#Html.TextBoxFor(model => model.FirstName, new { #maxlength = 7, #class = "numeric"})
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="spacer-short"></div>
</td>
<td>
#Html.LabelFor(model => model.LastName)
<div class="control">
#Html.TextBoxFor(model => model.LastName, new { #maxlength = 7, #class = "numeric"})
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="spacer-short"></div>
</td>
</tr>
</table>
#{ Html.RenderAction("Index", "Address", new {id = Model.AddressId});} //Renders the Address form part
<div class="spacer"></div>
<button type="submit" data-button="true" data-button-icon="ui-icon-disk" class="">Create</button>
<button type="button" data-button="true" data-button-icon="ui-icon-circle-close" class="button-cancel">Cancel</button>
}
ADDRESS VIEW
#model Entities.Address
<table>
<tr>
<td>
#Html.LabelFor(model => model.Street)
<div class="control">
#Html.TextBox("Address.Street", Model.Street)
#Html.ValidationMessage("Address.Street")
</div>
<div class="spacer-short"></div>
</td>
<td>
#Html.LabelFor(model => model.Number)
<div class="control">
#Html.TextBox("Address.Number", Model.Number)
#Html.ValidationMessage("Address.Number")
</div>
<div class="spacer-short"></div>
</td>
</tr>
</table>
Then I have some validation metadata ([Required]) for person and address fields
A common mistake using #Html.Partial(...) and expecting validation errors to show up is not passing ViewData to that partial.:
#Html.Partial([ViewName], [EmailAddressObject], ViewData)
Try this:
#Html.EditorFor(Model.Street)
#Html.ValidationMessageFor(Model.Street)
instead of this:
#Html.TextBox("Address.Street", Model.Street)
#Html.ValidationMessage("Address.Street")
Try using Html.Partial(...) instead of Html.RenderAction(...) to render the partial view. This may be suppressing the validations.
Model
İmportant: Manage Nuget Packages
=>> JQuery.Validation
=>> Microsoft.JQueryUnobtrusive.Validation
install.
1) First step
using System.ComponentModel.DataAnnotations;
2)
public int Id { get; set; }
[Required(ErrorMessage = "* Kategori adı boş geçilemez.")]
[DisplayName("Kategori Adı")]
public string CategoryName { get; set; }
[Required(ErrorMessage = "* Kategori açıklaması boş geçilemez.")]
[DisplayName("Kategori Açıklaması")]
public string Description { get; set; }
3)
if (model != null && ModelState.IsValid)
{
var categoryCreate = new Categories
{
//code
};
_CategoriesService.Create(categoryCreate);
}
4)
Add ViewModel
#model Models.CategoryViewModel
After
#Html.TextBoxFor(model => model.CategoryName, new { #class = "form-control input-sm", id = "categoryTitle", #placeholder = "Kategori adını giriniz.", #type= "text", #required=true })
#Html.ValidationMessageFor(model => model.CategoryName, "", new { #class = "error-message" })
#Html.TextBoxFor(model => model.Description, new { #class = "form-control input-sm", id = "categoryArticle", #placeholder = "Kategori açıklamasını giriniz.", #type = "text", #required = true })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "error-message" })
In my case, I was missing
<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>
Once I put that in my _layout.cshtml file, it started working even with partial views.

How to pass data from View to Controller in MVC 3

I have created a ViewModel with two things, a Contact and a list of Phones for that Contact.
My goal is to add data for a new Contact, and add a few Phones, and then save by a Controller action.
I've edited the scaffolded Create.cshtml for my Contact, added a grid for the phones. Added a javascript for creating the phones. So far so good.
The problem is when I click the Create button, and I get back to the Controller, I get no Phones. How do I (in the View) add the phone-rows to my IEnumerable?
EDIT:
Took out code in view that was not correct in this context.
My ViewModel:
public class ContactViewModel
{
public Contact Contact {get; set;}
public IEnumerable<Phone> Phones { get; set; }
}
My view:
#model PilotKibsNet.Controllers.ContactViewModel
<script type="text/javascript" src="../../Scripts/jquery-1.5.1.js"></script>
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<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 Add() {
$("#tbl > tbody:last").append("<tr><td>" + $("#Number").val() + "</td><td>" + $("#Kind").val() + "</td><td></td></tr>");
$("#Number").val("");
$("#Kind").val("");
}
</script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Contact</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Contact.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Contact.Name)
#Html.ValidationMessageFor(model => model.Contact.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Contact.Address)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Contact.Address)
#Html.ValidationMessageFor(model => model.Contact.Address)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Contact.City)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Contact.City)
#Html.ValidationMessageFor(model => model.Contact.City)
</div>
<legend>Phone numbers</legend>
<label>Number :</label>
#Html.TextBox("Number")
<label>Kind :</label>
#Html.TextBox("Kind")
<input type="button" value="Add" onclick="Add()" />
<table id="tbl">
<tr>
<th>
Phone
</th>
<th>
Kind
</th>
<th></th>
</tr>
<tbody>
</tbody>
</table>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
And then, in by Controller action, the Contact has the data, but the Phone is an empty list.
[HttpPost]
public ActionResult Create(ContactViewModel contactViewModel)
{
if (ModelState.IsValid)
{
contactViewModel.Contact.id = Guid.NewGuid();
db.Contacts.AddObject(contactViewModel.Contact);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(contactViewModel.Contact);
}
How do I get the Phones back to the server?!?
You have only display templates for those Phones collection. No value at all will be sent to the server. You could use hidden fields if the user is not supposed to edit the values or textboxes if he is.
Also I would replace this foreach loop in your view by an editor template:
if (Model != null)
{
#Html.EditorFor(x => x.Phones)
}
and then I will define an editor template which would be rendered for each element of the Phones collection (~/Views/Shared/EditorTemplates/Phone.cshtml):
#model Phone
<tr>
<td>
#Html.DisplayFor(x => x.Number)
#Html.HiddenFor(x => x.Number)
</td>
<td>
#Html.DisplayFor(x => x.Type)
#Html.HiddenFor(x => x.Type)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = Model.id }) |
#Html.ActionLink("Details", "Details", new { id = Model.id }) |
#Html.ActionLink("Delete", "Delete", new { id = Model.id })
</td>
</tr>
I have used hidden fields here to persist the values of the model so that when you post the form to the server they would be sent.
Another and IMHO better approach if the user is not supposed to edit those values in the table is to simply refetch them in your POST action from your database.

Page with Multiple Submit Buttons and one Get/Post Action Method

I am new to MVC, so please forgive me if I am being so noob :).
In my new project, I want to make a 'Create Song' page which, of course, creates a new song. In model design, one song can have many artists. So, on the create song page, a user should be able to search for artists and add artists from the search results by pressing the 'Add' links of artists in the search result.
Currently, I have two submit buttons in form which are "Submit" and "SearchArtist" and they call http POST "Create" action method. A ViewModel object(CreateSongScrnData) is used to post the screen data. And it's all working ok. But when I try to add an artist from Artist search result, using #Url.Action passing ViewModel data to "Create" http get method, the viewmodel object parameter is always null when it come into the actiona method. Please help me with some advice and enlighten me if I am missing some concepts. Thank you so much in advance.
Code is as follows.
public ActionResult Create(CreateSongScrnData modelData, Int32? artistIDToAdd)
{
if (modelData != null && artistIDToAdd != null)
{
var artist = db.Artists.Find(artistIDToAdd);
modelData.Song.Artists.Add(artist);
}
ViewBag.GenreID = new SelectList(db.Genres, "GenreID", "Name");
ViewBag.AlbumID = new SelectList(db.Albums, "AlbumID", "Name");
return View(modelData);
}
[HttpPost]
public ActionResult Create(CreateSongScrnData modelData)
{
switch (modelData.SubmitCommand)
{
case "AddNewSong":
if (ModelState.IsValid)
{
db.Songs.Add(modelData.Song);
db.SaveChanges();
return RedirectToAction("Index");
}
break;
default:
modelData.SearchResult = db.Artists.Where(a => a.Name.Contains(modelData.ArtistSearchString)).ToList();
break;
}
ViewBag.GenreID = new SelectList(db.Genres, "GenreID", "Name", modelData.Song.GenreID);
ViewBag.AlbumID = new SelectList(db.Albums, "AlbumID", "Name", modelData.Song.AlbumID);
return View(modelData);
}
Code snippet of search in the view is as follows:
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.Song.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Song.Name)
#Html.ValidationMessageFor(model => model.Song.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Song.MyanmarName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Song.MyanmarName)
#Html.ValidationMessageFor(model => model.Song.MyanmarName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Song.Genre)
</div>
<div>
#Html.DropDownList("GenreID", "Choose Genre")
#Html.ValidationMessageFor(model => model.Song.GenreID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Song.AlbumID, "Album")
</div>
<div class="editor-field">
#Html.DropDownList("AlbumID", "Choose Album")
#Html.ValidationMessageFor(model => model.Song.AlbumID)
</div>
<div class="editor-label">
<p>Sing by this artists:</p>
#if (Model.AddedArtists != null)
{
<table><tr><th>Name</th></tr>
#foreach (var item in Model.AddedArtists)
{
<tr><td>#item.Name</td></tr>
}
</table>
}
</div>
<div style=" border-top:1px solid #ccc; width: 400px; height:auto; margin-top:30px; margin-bottom:30px;"></div>
<div>
<p>Search and add artists</p>
#Html.TextBoxFor(model => model.ArtistSearchString)
<input type="submit" name="SubmitCommand" value="SearchArtist" class="cancel" />
#if (Model.SearchResult != null)
{
<div>
<table><tr><th>Name</th><th></th></tr>
#foreach (var item in Model.SearchResult)
{
<tr><td>#item.Name</td>
<td>Add</td>
</tr>
}
</table>
</div>
}
</div>
<div style=" border-top:1px solid #ccc; width: 400px; height:auto; margin-top:30px; margin-bottom:30px;"></div>
<p>
<input type="submit" name="SubmitCommand" value="AddNewSong" />
</p>
}
I think you are mixing too things in a single form.
Solution 1)
Create a first step where user insert data and create song.
Create a second step where user add artists to the song.
Solution 2)
Let to the submit button the function to store data.
For the search of artist use a ajax compnent like this:
http://harvesthq.github.com/chosen/

Resources