Data-binding for collections in Create View of ASP.NET MVC - c#

I'm trying to add a survey feature to my ASP.NET MVC 5 web application so that users can create surveys with custom questions to send out to other users. The problem is, I'm having trouble allowing users to add questions to the survey on the Create Survey view.
I've seen ways to do this on the "Edit" View, when an instance of the model has already been created, but I want the user to be able to create questions on the survey before adding the survey to the database.
This is my Survey Model:
public class Survey
{
public int SurveyId { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public List<Question> Questions { get; set; }
public List<Response> Responses { get; set; }
}
and this is my Question model:
public class Question
{
public int QuestionId { get; set; }
public int SurveyId { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public QuestionType QuestionType { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime LastModified { get; set; }
public List<Answer> Answers { get; set; }
}
Honestly, the code I have right now in Create.cshtml is garbage because I don't really know where to start but here it is anyways:
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Survey</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Author, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Author, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Author, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StartDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StartDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EndDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EndDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EndDate, "", new { #class = "text-danger" })
</div>
</div>
<h4 class="well well-small">
Questions
</h4>
<button class="toggle-add-question" data-target="#add-question" data-toggle="modal" type="button">
<i class="icon-plus"></i> Add Question
</button>
<div class="modal" id="add-question" tabindex="-1">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Add Question</h3>
</div>
<div class="modal-body">
<div class="row">
<form method="post">
<fieldset>
<div class="form-group">
<label for="Title">Title</label>
<input type="text" id="Title" name="Title" data-bind="value: title" />
</div>
<div class="form-group">
<label for="Type">Type</label>
<select id="Type" name="Type" data-bind="value: type">
<option>Yes/No</option>
<option>Number</option>
</select>
</div>
</fieldset>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" data-dismiss="modal" />
</div>
</div>
</form>
</div>
<div class="row">
<div class="span6">
<textarea id="Body" name="Body"></textarea>
</div>
</div>
</div>
</div>
<table class="table">
<tr>
<th>
Question Title
</th>
<th>
Question Body
</th>
<th>
Question Type
</th>
</tr>
#if (Model.Questions != null)
{
for (var i = 0; i < Model.Questions.Count(); i++)
{
<tr>
#Html.HiddenFor(x => Model.Questions[i].QuestionId)
<td>
#Html.TextBoxFor(x => Model.Questions[i].Title)
</td>
<td>
#Html.TextBoxFor(x => Model.Questions[i].Body)
</td>
<td>
#Html.TextBoxFor(x => Model.Questions[i].QuestionType)
</td>
</tr>
}
}
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
What I want is for the user to be able to click the "Add Question" button, have the modal with the question fields pop up, and then for the user to be able to click "save" and have the modal exit and the new question appear in the table. Right now, I'm getting the error that the object reference is not set to an instance of the object, which makes perfect sense because the Survey object hasn't been created yet, but I'm unsure of how to do this differently. (Without the table, the modal view pops up and everything but no questions are added).
Any help would be greatly appreciated, thanks!

You could update the table, when saving the modal popup by combining AJAX and Partial Views (called partials from here on).
The table that holds your question data could sit in a partial with its own view model that takes in the questions you want to render. You can keep the markup as is.
On your page, where the table is now, replace that with a containing div that has the partial inside.
When you save the modal that adds a new question, you could use an AJAX call (trigger on click) to hit your Controller, save the new question record (with whatever validation you need) and return the table partial with a new view model, populated with the questions in your DB (which would include the new you just saved).
In the success callback of the AJAX call, populate the container div with the new partial and view model, then close the popup. The page will show a new question in the table without having go through a whole page cycle.

Related

ASP.NET core all model values are null when passing a model to the view

Goal: I have a page that I want to have a return url passed through the model of the view so upon completion of the form, it will return to the previous url. The page is a address validation and add it to the account as a saved address.
Flow of the page: You are presented with an address form to fill out. on completion, you will have a button that will call to a controller method that will verify with FedEx via API, and then if valid, it will let you save the address.
Issue: once you press the Verify Address button, it seems to have an issue with sending the form data to the controller.
HTTPGET:
public ActionResult AddShippingAddress(string strReturnURL)
{
// get states
ViewBag.states = GetStates();
DeliveryAddressModel model = new DeliveryAddressModel();
model.strReturnAddress = strReturnURL;
return View(model);
}
AddShippingAddress.chshtml
#model EcommerceWebsite.Models.Home.DeliveryAddressModel
#{
ViewBag.Title = "Shipping Address";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<div class="container">
<partial id="ValidateAddress"></partial>
#using (Html.BeginForm())
{
<h4>Shipping Address</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<h5>Name</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Attention To</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strAttnTo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strAttnTo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Street</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strStreet1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strStreet1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Street 2</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strStreet2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strStreet2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>City</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strCity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strCity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#{
IEnumerable<SelectListItem> dataItems = ViewBag.states;
}
<div class="form-group">
<h5>State</h5>
<div class="col-md-10">
#Html.DropDownListFor(model => model.State.IntStateId, dataItems, "-- Select --", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.State.IntStateId, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<h5>Zip</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strZip, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strZip, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Phone Number</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strPhoneNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strPhoneNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Set as Default</h5>
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.blnIsDefault)
#Html.ValidationMessageFor(model => model.blnIsDefault, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" class="btn btn-primary" data-ajax-method="get" data-toggle="ajax-modal"
data-url="#Url.Action("GetValidationOnAddress", new { model = Model })">
Verify Address
</button>
</div>
</div>
}
</div>
<script>
$(function () {
var PlaceHolderElement = $('#ValidateAddress');
$('button[data-toggle="ajax-modal"]').click(function (event) {
event.preventDefault();
var url = $(this).data('url');
// get the form containing the submit button
var form = $(this).closest('form')
// serialize all the fields in the form
var model = form.serialize();
// the the request to the url along with the form (model) data
$.get(url, model).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
//$('#ValidateAddress').modal('show');
})
})
})
</script>
Here is the partial:
#model EcommerceWebsite.Models.Home.DeliveryAddressModel
<div class="modal fade" id="ValidateAddress">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="ValidateAddressLabel">Validate Address</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#using (Html.BeginForm("AddShippingAddressToUser", "Home"))
{
#Html.HiddenFor(x => x.strName)
#Html.HiddenFor(x => x.strAttnTo)
#Html.HiddenFor(x => x.strStreet1)
#Html.HiddenFor(x => x.strStreet2)
#Html.HiddenFor(x => x.strCity)
#Html.HiddenFor(x => x.State.StrStateCode)
#Html.HiddenFor(x => x.State.StrStateName)
#Html.HiddenFor(x => x.State.IntStateId)
#Html.HiddenFor(x => x.strZip)
#Html.HiddenFor(x => x.strPhoneNumber)
#Html.HiddenFor(x => x.blnIsDefault)
<div class="modal-body">
<form action="Create">
<div class="form-group">
#if (Model.ErrorMessage == null)
{
<h5>#Model.strName</h5>
#if (Model.strAttnTo != null)
{<h5>#Model.strAttnTo</h5>}
<h5>#Model.strStreet1</h5>
#if (Model.strStreet2 != null)
{<h5>#Model.strStreet2</h5>}
<h5>#Model.strCity</h5>
<h5>#Model.State.StrStateCode</h5>
<h5>#Model.strZip</h5>
<h5>#Model.strPhoneNumber</h5>
<div class="modal-footer">
<button type="submit" value="Save" class="btn btn-primary">Save</button>
<button type="button" value="Edit" class="btn btn-secondary" data-dismiss="modal">Edit</button>
</div>
}
else
{
<h4>#Model.ErrorMessage</h4>
}
</div>
</form>
</div>
}
</div>
</div>
</div>
When all is said and done and the get validation button is pressed, it's supposed to send all the data to the controller and Verify the address with FedEx. But everything is null..
Now something to note, when I change the return of the httpget to return View(); everything works except it doesn't send the URL.
Update:
The AddShippingAddressToUser() hasn't even been called yet. The error lies somewhere in lines 101 - 102. Inside the button or the line 618 on the home controller.
Update: Here's the Model
public class DeliveryAddressModel
{
//[Required]
//[Display(Name = "First & Last Name")]
public string strName { get; set; }
//[Display(Name = "Attention To")]
public string strAttnTo { get; set; }
//[Required]
//[Display(Name = "Street 1")]
public string strStreet1 { get; set; }
//[Display(Name = "Street 2")]
public string strStreet2 { get; set; }
//[Required]
//[Display(Name = "City")]
public string strCity { get; set; }
//[Required]
//[Display(Name = "State")]
public Tstate State { get; set; }
//[Required]
//[Display(Name = "Zipcode")]
public string strZip { get; set; }
//[Required(ErrorMessage = "You must provide a phone number")]
//[Display(Name = "Phone Number")]
//[DataType(DataType.PhoneNumber)]
//[RegularExpression(#"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid phone number")]
public string strPhoneNumber { get; set; }
public bool blnIsDefault { get; set; }
public string ErrorMessage { get; set; }
public string strReturnAddress { get; set; }
}
First thing, since your form's function isnt a retrieval operation and a creational operation, use the http verb POST and not GET. Replace the HttpVerb filter above your action from HttpGet to HttpPost.
Second add this:
#using (Html.BeginForm("AddShippingAddressToUser", "Home", FormMethod.Post))
Alternatively,
#using (Html.BeginForm("AddShippingAddressToUser", "Home", FormMethod.Get))
Before your model in the action add: [FromQuery]

Insert data into database from another models view

I have two model classes for my project,
public class BookModel
{
public Int64 ISBN { get; set; }
public DateTime AddedDate { get; set; }
public bool isActive { get; set; }
public int Quantity { get; set; }
public int? FormatID { get; set; }
public virtual FormatModel Format { get; set; }
}
and
public class FormatModel
{
public FormatModel()
{
Books = new HashSet<BookModel>();
}
public int ID { get; set; }
public string Value { get; set; }
public virtual ICollection<BookModel> Books { get; }
}
I want to create a modal in my Create.cshtml file to add a new format if the specified format doesn't exist.
How can I create a Submit button for my modal to add the format in FormatModel?
This is my view:
#model RookBookMVC.Models.BookModel
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.ReturnUrl = "/Book/Create";
}
<h2>Create</h2>
#using (Html.BeginForm("Create", "Book", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>BookModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.FormatID, "FormatID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="input-group col-md-10">
#Html.DropDownList("FormatID", null, "Select Book Format", htmlAttributes: new { #class = "form-control" })
<div class="input-group-append">
<button type="button" class="btn btn-secondary" data-toggle="modal" data-target="#exampleModalCenter">
Add New
</button>
</div>
</div>
#Html.ValidationMessageFor(model => model.FormatID, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.ISBN, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ISBN, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ISBN, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Quantity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Quantity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
#using (Html.BeginForm("Create", "Format", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Add New Format</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
#Html.LabelFor(model => model.Format.Value, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Format.Value, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Format.Value, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<input type="submit" value="Create Format" class="btn btn-default" />
</div>
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
after I click on the 'Create Format' button. it returns false for ModelState.IsValid and doesn't add any data to my database
What should I do for making 'Create Format' Button make a new Entity for Format and save it in my database?
for Additional I need to create two models via a single page
You might have to create a View Model and pass the view model property as parameter to the Action - Format/ Create post.
ViewModel property:
public string FormatValue { get; set; }
Modal view:
#Html.EditorFor(model => model.FormatValue, new { htmlAttributes = new { #class = "form-control" } })
Controller code with parameter as the same name as the view model property being passed from the modal form:
[HttpPost]
public ActionResult Create(string formatValue)
{
using (var dataContext = new YourDbContextModel())
{
FormatModel fmtModel = new FormatModel();
fmtModel.Value = formatValue;
// rest of your code to save data
}
}
public class MYViewModel{ public string FormatValue { get; set; } }
Create.cshtml
#model MYViewModel
<div>
#Html.EditorFor(model => model.FormatValue, new { htmlAttributes = new { #class = "form-control" } })
</div>
Do You Mean something Like that?
OR
public class MYViewModel{
public string FormatValue { get; set; }
Public BookModel Book {get; set;}
}

Empty POST model argument when using EditorFor

I am trying to submit a form that incorporates an #Html.EditorFor element. If I remove the EditorFor element, my POST controller argument passes data correctly, but once implemented, my entire model argument shows as null in the POST controller.
Here's the model I'm trying to pass:
public class Checkout
{
public int CheckoutID { get; set; }
public string Requestor { get; set; }
public DateTime? DateRequested { get; set; }
public List<CheckoutReceiver> Receivers { get; set; }
}
The form element on page:
#model PRI.Models.Checkout
#using (Html.BeginForm("CreateCheckout", "API/CheckoutRequest", FormMethod.Post, new { id = "pri-form" }))
{
<div id="checkout-request">
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div id="checkout-info" class="form-horizontal">
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(m => m.CheckoutID)
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(m => m.Receivers)
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input id="create-checkout-submit" type="submit" value="Confirm transfer" class="btn btn-danger right" style="margin: 10px;" />
</div>
</div>
</div>
</div>
}
If I remove the #Html.EditorFor(m => m.Receivers), and add data to the #Html.TextBoxFor(m => m.CheckoutID) then that passes correctly to my Post Controller, so obviously my EditorFor is messing things up:
Here's the POST controller (i put a breakpoint right after it enters this so I can check the checkout argument):
[System.Web.Http.HttpPost]
[ValidateAntiForgeryToken]
[System.Web.Http.ActionName("CreateCheckout")]
public Checkout Create(Checkout checkout)
{
var request = new Checkout();
return request;
}
Here's my CheckoutReceiver Editor template (removed some input elements for brevity):
#model PRI.Models.CheckoutReceiver
#using (Html.BeginCollectionItem("Receivers"))
{
<div class="form-horizontal">
#Html.HiddenFor(model => model.ID)
#Html.HiddenFor(model => model.CheckoutID)
<h4 class="contact-header">#Model.ContactType</h4>
<div class="form-group">
<div class="col-md-5">
<span class="form-header">Last Name</span>
#Html.TextBoxFor(model => model.LastName, new { #class = "box-customer form-control ignore", placeholder = "Last name" })
</div>
<div class="col-md-5">
<span class="form-header">First Name</span>
#Html.TextBoxFor(model => model.FirstName, new { #class = "form-control ignore", placeholder = "First name" })
</div>
<div class="col-md-2">
<span class="form-header">Middle Initial</span>
#Html.TextBoxFor(model => model.MiddleInitial, new { #class = "form-control ignore", placeholder = "M.I." })
</div>
</div>
</div>
}
Where am I going wrong, and why is my EditorFor causing my Checkout POST argument to be null on submit?
Thanks!
Maybe you should check this question. You should add an editor for an
IEnumerable<CheckoutReceiver> instead of an editor for CheckoutReceiver.

Creating a subform to upload update another entity

this is driving me mad because it seems like such a basic thing, and yet I cannot for the life of me google it out...
I have Two Models in the Portfolio Part of my MVC website
public class PortfolioEntry
{
public int ID { get; set; }
[Display(Name="Project Name")]
public string Name { get; set; }
[Display(Name="Created for")]
public string Client { get; set; }
public string Description { get; set; }
[Display(Name ="Started at")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime Start { get; set; }
[Display(Name ="Ended by")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime End { get; set; }
[Display(Name ="Skills used")]
public string Category { get; set; }
[Display(Name ="GitHub Link")]
public string GitHubLink { get; set; }
[Display(Name ="Solution Screenshots")]
public virtual ICollection<ScreenShot> ScreenShots { get; set; }
}
And the second one:
public enum ScreenShotType
{
[Display(Name = "Use case Diagram")]
UseCase,
[Display(Name = "Behaviour Diagram")]
Behavior,
[Display(Name ="Class Diagram")]
ClassStructure,
[Display(Name ="Main View")]
MainPage,
[Display(Name = "Additional View")]
SomthingCool
}
public class ScreenShot
{
public int ID { get; set; }
public string Description { get; set; }
[Display(Name="Screenshot Type")]
public ScreenShotType Type { get; set; }
public string ImageURL { get; set; }
public int Sorting { get; set; }
public int PortfolioEntryID { get; set; }
}
}
Now what I want to do is create a subform that allows me to on the fly Upload a ScreenShot and create a new record in the database for it (you click browse..., select the photo, fill in the info for it and click "Upload").
Then return the "Main" form so I can either upload another one or just save the whole thing altogether.
How should I go about it? I Tried creating a new action in the controller:
public async Task<ActionResult> UploadPhoto([Bind(Include = "ID,Name,Client,Description,Start,End,GitHubLink")] PortfolioEntry portfolioEntry, HttpPostedFileBase uploadedFile, string description, int sorting)
{
if (uploadedFile!=null && uploadedFile.ContentLength>0 && uploadedFile.ContentType.Contains("image"))
{
string extension = Path.GetExtension(uploadedFile.FileName.ToString().ToLower());
string fileName = "PorfolioImage" + String.Format("{0:D5}", db.Photos.Count()) + extension;
var path = Path.Combine(Server.MapPath("~/Pictures/ScreenShots"), fileName);
uploadedFile.SaveAs(path);
var screenshotToAdd = new ScreenShot
{
Description = description,
Sorting = sorting,
PortfolioEntryID = portfolioEntry.ID,
ImageURL = fileName
};
await db.SaveChangesAsync();
}
return(View(portfolioEntry));
}
But:
1. It does not see the uploaded file
2. Even if it did see the file it does not seem to register the Entity from the Bind
I've seen one solution by: mkozicki but before I re-write the methods I'd like to know if it is the path I should take.
Adam
EDIT: As per the follow up adding the View:
#model KoscielniakInfo.Models.PortfolioEntry
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>PortfolioEntry</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Start, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Start, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Start, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.End, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.End, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.End, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.GitHubLink, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.GitHubLink, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.GitHubLink, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1 col-md-10">
<table>
<tr>
#{
int cnt = 0;
foreach (var category in ViewBag.Categories)
{
if (cnt++ % 3 == 0)
{
#Html.Raw("</tr><tr>")
}
#Html.Raw("<td>")
<input type="checkbox"
name="selectedCategories"
value="#category.Name"
#(Html.Raw(category.Selected ? "checked=\"checked\"" : "")) />
#category.Name
#Html.Raw("</td>")
}
#Html.Raw("</tr>")
}
</table>
</div>
</div>
<div class="form-group">
<div id="newCats" class="col-md-10 col-md-offset-1">
<div id="newCat">
<h5>
New Category
</h5>
<input type="text" name="newCategories" /><br />
</div>
</div>
<div class="col-md-10 col-md-offset-1">
<input id="clone" type="button" value="More Categories" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
#*=================================This is the form Group for adding the photo ============================================*#
<div class="form-group">
<div class="row">
<div class="col-md-offset-2 col-md-3">
Description:
</div>
<div class="col-md-7">
<input type="text" name="description" id="description" />
</div>
</div>
<div class="row">
<div class="col-md-offset-2 col-md-3">
screenType:
</div>
<div class="col-md-7">
<input type="text" name="screenType" />
</div>
</div>
<div class="row">
<div class="col-md-offset-2 col-md-3">
Sorting:
</div>
<div class="col-md-7">
<input type="number" name="sorting" id="sorting" />
</div>
</div>
<div class="row">
<div class="col-md-offset-2 col-md-3">
Image:
</div>
<div class="col-md-7">
<input type="file" name="uploadedFile" />
</div>
<input type="button" value="Create" onclick="location.href='#Url.Action("UploadPhoto", "PorfolioEntries")'" />
</div>
</div>
//=============================================Ends Here =========================================================================
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$('#clone').click(function () {
$('#newCat').last().clone().appendTo('#newCats')
})
</script>
}

Adding another form to a view on button clicked

I have a Create view which contains a form. I want to give the user two options, save which simply saves the form and redirects to Index or add more tickets which will show another identical form in the view. I am unsure where to start with this, should I save the first ticket details then refresh the page? Or is there a way to have a second form hidden until add more tickets is selected then save all forms at once? I know this is quite vague but I've no idea where to start, but any advice would be great
Here is my model;
public class Ticket
{
public int TicketID { get; set; }
[Required]
[ForeignKey("Event")]
//foreign key
public int EventID { get; set; }
[Required]
public string Description { get; set; }
[Required]
public float Price { get; set; }
//navigation property
public virtual Event Event { get; set; }
//navigation property
public ICollection<OrderDetails> OrderDetails { get; set; }
}
Here is my view so far;
#model GeogSocSite.Models.Ticket
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Ticket</h4>
<hr />
#Html.HiddenFor(model => model.EventID)
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Price, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Price, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Price, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
My choice in this situation is using appropriate view model(as #StephenMuecke ) sugested) and using Bootsrtaap modal(here) to show hidden fields.

Categories