Why my button is not calling action in the controller? - c#

I have EDITSTORIES partial view which must post data to UpdateStories action in Stories controller but it doesn't. It doesn't even hit the breakpoint.
#using (Html.BeginForm("UpdateStories", "Stories", FormMethod.Post, new{enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Stories</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.Image, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Image, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Image, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Story, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Story, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Story, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update" class="btn btn-default" />
</div>
</div>
</div>
}
Action:
[HttpPost]
public ActionResult UpdateStories(Stories st)
{
ViewBag.Grid= bo.GetAllImages();
if (bo.UpdateImages(st))
{
ViewBag.Data = "Updated successfully";
}
else
{
ViewBag.Data = "Update failed";
}
ViewBag.Style = "display:none";
return View("GetStories", st);
}
}
It's inside the GetStories which is the main view. It's been a long day and still, it hasn't been done. Please help me with it.
Update:
Routes:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Stories", action = "AddStories", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "ShowStories",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Stories", action = "ShowStories", id = UrlParameter.Optional }
);
Update:
View: GetStories
#model HimHer.Models.Stories
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (#Html.BeginForm("GetStories", "Stories", FormMethod.Get))
{
#Html.AntiForgeryToken()
<div style="#ViewBag.Style">
#{
Html.RenderPartial("EditStories", Model);
}
</div>
<hr />
var listData = (List<HimHer.Models.Stories>)ViewBag.Grid;
WebGrid wgImages = new WebGrid(listData, rowsPerPage: 20);
#wgImages.GetHtml(tableStyle: "table table-condensed table-bordered table-striped table-responsive",
columns: wgImages.Columns(
wgImages.Column
(columnName: "Image", header: "Image"),
wgImages.Column
(columnName: "Story", header: "Story"),
wgImages.Column
(columnName: "Image", header: "Download", format: (testItem) => Html.ActionLink("Download", "DownloadStories", new { filename = testItem.Image })),
wgImages.Column
(header: "Edit", format: (testitem) => Html.ActionLink("Edit", "EditStories", new { ID = testitem.ID, Story = testitem.Story, Image = testitem.Image, HiddenID = 1 }))
)
);
}
<h2>Index</h2>

You code will generate 2 forms and they are nested!.
<form action="/Stories/GetStories">
<form action="/Stories/UpdateStories">
<input type="submit" />
</form>
</form>
Nested forms are invalid! This is the reason, when you click the submit button from inner form from the partial view, it is submitting to the action method defined for the outer form.
You should not be nesting forms. So move out the call to the RenderPartial outside of your BeginForm call.
Looking at the code you shared,there is no need to have the form tag in the main view as you do not have any form data you have to submit. So simply remove that.
If you absolutely want another form in the main view, make sure that, it is not creating a nested form situation. You can have 2 forms parallel in the same view
#using (#Html.BeginForm("GetStories", "Stories", FormMethod.Get))
{
<!-- Some form elements needed for this form -->
}
#{ Html.RenderPartial("EditStories", Model); }

Related

HttpPostedFileBase returning null from AJAX post in ASP.NET MVC App [duplicate]

This question already has answers here:
How to upload files using ajax to asp.net mvc controller action
(2 answers)
How to append whole set of model to formdata and obtain it in MVC
(4 answers)
Closed 4 years ago.
I've done a little research on this and it always says the same thing, make sure you have enctype for "multipart/form-data" when trying to do an ajax post with a file to an mvc controller. As far as I can tell, I have done that yet still when I run through the debugger, HttpPostedFileBase always returns null. I'm not seeing where I'm missing something probably very obvious.
Here is the razor view form.
#using (Html.BeginForm("Edit", "Story", FormMethod.Post, new { encType = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(x => x.StoryId)
<div class="form-group">
<div class="row">
<div class="col-sm-4">
<div class="card">
<div class="card-body">
<p class="card-text">Add/Edit cover art to your story</p>
<img class="img-thumbnail" src="~/Imgs/#Model.CoverArt" />
<input type="file" id="file" name="file" class="form-control" />
</div>
</div>
</div>
<div class="col-sm-8"></div>
</div>
</div>
<div class="form-row">
<div class="col-6">
#Html.LabelFor(model => model.Title, htmlAttributes: new { #class = "control-label text-muted" })
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
<div class="col-3">
#Html.LabelFor(x => x.Genre, htmlAttributes: new { #class = "control-label text-muted" })
#Html.DropDownListFor(x => x.Genre, new SelectList(Model.Genres, "Id", "Name"), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Genre, "", new { #class = "text-danger" })
</div>
<div class="col-3">
#Html.Label("Visibility", htmlAttributes: new { #class = "control-label text-muted" })
<i class="fa fa-question-circle-o" data-toggle="popover" title="What does visibility mean?" data-placement="right" data-content="Visibility determines whether other users can see this story or not. Public means any other user can read, vote, and review the story. You can change this to private, which will hide the story from other users. You, as the author, will be able to see all of your stories - both public and prviate - under your account."></i>
#Html.DropDownListFor(x => x.Visibility, new SelectList(Model.Visibilities, "Id", "Name"), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Visibility, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-row mt-3">
<div class="col-6">
#Html.Label("Story Type", htmlAttributes: new { #class = "control-label text-muted" })
#Html.DropDownListFor(x => x.StoryType, new SelectList(Model.StoryTypes, "Id", "Name"), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StoryType, "", new { #class = "text-danger" })
</div>
<div class="col-6">
#Html.Label("Target Age Range", htmlAttributes: new { #class = "control-label text-muted" })
#Html.DropDownListFor(x => x.StoryAgeRange, new SelectList(Model.StoryAgeRanges, "Id", "Name"), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StoryAgeRange, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-row mt-5">
<div class="col-12">
#Html.Label("Write below", htmlAttributes: new { #class = "control-label text-muted" })
#Html.TextAreaFor(model => model.Content, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Content, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-row mt-3">
<div class="btn-group">
#Html.ActionLink("Cancel", "Index", "Story", null, new { #class = "btn btn-red" })
<input type="button" id="editStoryBtn" value="Edit story" class="btn btn-blue" />
<a class="btn btn-link ml-auto" href="#Url.Action("PublishingRules", "Legal")">Publishing Guidelines</a>
</div>
</div>
}
Here is the javascript for the ajax call (and the function I use to get the filename):
//get the filename of the uploaded file
var fullPath = document.getElementById('file').value;
if (fullPath) {
var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
var filename = fullPath.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
filename = filename.substring(1);
}
}
//create the new story object
var editedStory = {
__RequestVerificationToken: token,
StoryId: storyId,
CoverArt: filename,
Title: $("input[name='Title']").val(),
Content: CKEDITOR.instances.Content.getData(),
Genre: $('#Genre').val(),
Visibility: $('#Visibility').val(),
StoryType: $('#StoryType').val(),
StoryAgeRange: $('#StoryAgeRange').val(),
WordCount: finalWordCount
}
//post the edited story to the controller
$.ajax({
url: "/story/edit/" + storyId,
type: 'POST',
data: editedStory,
success: function (data) {
window.location.href = data.Url;
},
error: function (error) {
console.log("error is " + error);
}
});
And here is the controller.
//POST story/edit/5
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Edit (EditStoryViewModel viewModel, HttpPostedFileBase file)
{
//confirm model state is valid
if (ModelState.IsValid)
{
//find the correct story by the id and include the reference tables
var StoryToEdit = dbContext.Stories.SingleOrDefault(x => x.Id == viewModel.StoryId);
//verify file upload
if (file != null)
{
StoryToEdit.CoverArt = StoryToEdit.Id + Path.GetExtension(file.FileName);
file.SaveAs(Server.MapPath("/Imgs/") + StoryToEdit.CoverArt);
}
StoryToEdit.Title = viewModel.Title;
StoryToEdit.Content = viewModel.Content;
StoryToEdit.GenreId = viewModel.Genre;
StoryToEdit.StoryAgeRangeId = viewModel.StoryAgeRange;
StoryToEdit.StoryTypeId = viewModel.StoryType;
StoryToEdit.VisibilityId = viewModel.Visibility;
StoryToEdit.WordCount = viewModel.WordCount;
StoryToEdit.UpdatedAt = DateTime.Now;
dbContext.Entry(StoryToEdit).State = EntityState.Modified;
dbContext.SaveChanges();
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Details", "Story", new { id = StoryToEdit.Id });
return Json(new { Url = redirectUrl });
}
else
{
return View(viewModel);
}
}
What's going wrong because the file is never being saved (everything else works).
When you want to post multipart form-data using XMLHttpRequest or a wrapper that uses it (like jQuery). You need to create a FormData object and add the files and formdata you want to send to the server. Only then the data is being sent accordingly to the server.
There are already some answers on how to use the FormData object
Sending multipart/formdata with jQuery.ajax
https://www.mkyong.com/jquery/jquery-ajax-submit-a-multipart-form/

c# MVC code for the Editing Button, but clicking on the Edit button does not post it

I use the following code for the Editing Button, but clicking on the Edit button does not post it
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "PageID,GroupID,Title,ShortDescription,Text,Autor,Tags,Visit,ImageName,ShowInSlider,CreatDateTime")] Page page,HttpPostedFileBase imgUp)
{
if (ModelState.IsValid)
{
if (imgUp != null)
{
if (page.ImageName != null)
{
System.IO.File.Delete(Server.MapPath("/PageImages/" + page.ImageName));
}
page.ImageName = Guid.NewGuid() + Path.GetExtension(imgUp.FileName);
imgUp.SaveAs(Server.MapPath("/PageImages/" + page.ImageName));
}
pageRepository.UpdatePage(page);
pageRepository.save();
return RedirectToAction("Index");
}
....
I have separate data layer and repository and I use the following code for the Editing Pages Controller, but with clicking on the Edit button does not post form. Though it works well for creation and delete btn. my view code is:
<div class="form-horizontal">
<h4>Page</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.PageID)
#Html.HiddenFor(model => model.Visit)
#Html.HiddenFor(model => model.CreatDateTime)
#Html.HiddenFor(model => model.ImageName)
<div class="form-group">
#Html.LabelFor(model => model.GroupID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("GroupID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.GroupID, "", new { #class = "text-danger" })
</div>
</div>
....
<div class="form-group">
#Html.LabelFor(model => model.ImageName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="imgUp" id="imgUp"/>
#Html.ValidationMessageFor(model => model.ImageName, "", new { #class = "text-danger" })
#if (Model.ImageName != null)
{
<img src="/PageImages/#Model.ImageName" class="thumbnail" style="max-width:150px" />
}
.....
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
i trace my code and find this eror:
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Request","time":"2018-04-25T08:10:44.3663705Z","tags":{"ai.internal.sdkVersion":"web: 2.0.0.25000","ai.device.roleInstance":"Laptop-erfan","ai.operation.name":"GET PageGroup
above horizontal form tag is this code:
#model DataLayer.Page
#{
ViewBag.Title = "Edit";}<h2>Edit</h2>#using (Html.BeginForm("Edit", "Pages", FormMethod.Post, new { enctype = "multipart/form-data" })){ #Html.AntiForgeryToken()
As mentioned in the comments it doesn't look like you have a form in your view. You can add one using:
#using (Html.BeginForm()) {
<!-- form contentshere -->
}
BeingForm has several overloads as well that you can use to change where it goes to, form method (GET/PUT) and set html attributes.
You need to add the complete form page into a Form tag.
please Use
#using (Html.BeginForm()) {
//Put your complete code inside this form...
}
It will create the Form tag with specified actions and type.
You can also specific the custom action method and type of the method as well.

System.InvalidOperationException: When submitting a message

I am receiving the error message above. I have looked at other's issues and can't seem to pinpoint the error. Here is the code that I have for the controller. Here is the error that I am getting :
System.InvalidOperationException: The ViewData item that has the key 'RecieverID' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'
public ActionResult Create()
{
ViewBag.RecieverID = new SelectList(db.AspNetUsers, "Id", "Email");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "RecieverID,TEXT")] Message message)
{
if (ModelState.IsValid)
{
var mes = new Message
{
SenderID = User.Identity.GetUserId(),
DATETIMEMADE = DateTime.Now,
TEXT = message.TEXT
};
db.Messages.Add(mes);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ReceiverID = new SelectList(db.AspNetUsers, "Id", "Email", message.RecieverID);
return View(message);
}
After that here is my view for creating a message:
#model MUE.Models.Message
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Message</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.RecieverID, "RecieverID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("RecieverID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.RecieverID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TEXT, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TEXT, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TEXT, "", 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>
Not sure where the issue is coming from but any help would be greatly appreciated.
First off, and not to be a grammar Nazi, but it should be "Receiver" not "Reciever".
Second, model.RecieverID indicates a single field, not a collection.
"new SelectList(..." is collection.
Please refer to this:
MVC - Set selected value of SelectList
You could create a ViewModel for the page such as:
public class MyViewModel
{
public SelectList ReceiverList
public MUE.Models.Message ReceivedMessage
}
Assign your values in the controller and then do something like:
#Html.DropDownListFor(model => model.ReceivedMessage.ReceiverID, Model.ReceiverList, new { #class = "form-control" })

How can I return a view from another model in a controller?

I stumbled across a better way to display my comment form within the post window with <p id="createPostButton">#Html.Action("Create", "Comment", new { id = Model.PostId })</p> (I was originally just trying to create a button to take you to the comment page sending the post id). However, I now get an error when I try to pass back the post/details/{id} view in the CommentController. It keeps trying to look in comment or shared folders passing either post OR details/{id} instead of post/details/{id}.
Post/Details Razor HTML file:
#model FantaC.Models.Post
#{
ViewBag.Title = #Html.DisplayFor(model => model.PostName);
}
<h2>#Html.DisplayFor(model => model.PostName)</h2>
<div class="row">
<div class="col-md-8 whiteBorder scroll">
<div class="postName">
<h4>Written by: #Html.DisplayFor(model => model.UserName)</h4>
<img src="#Html.DisplayFor(model => model.PostImage)" />
</div>
<div class="postContent">
<p>#Html.DisplayFor(model => model.PostContent)</p>
</div>
</div>
<div class="col-md-4 whiteBorder scroll">
<h4>Comments</h4>
#foreach (var comment in Model.PostComments)
{
<h5>#Html.DisplayFor(modelItem => comment.UserName)</h5>
<h5>#Html.DisplayFor(modelItem => comment.CommentSubject)</h5>
<p>#Html.DisplayFor(modelItem => comment.CommentContent)</p>
<p>
#Html.ActionLink("Edit", "../Comment/Edit", new { id = comment.CommentId }) |
#Html.ActionLink("Details", "../Comment/Details", new { id = comment.CommentId }) |
#Html.ActionLink("Delete", "../Comment/Delete", new { id = comment.CommentId })
</p>
}
<p id="createPostButton">#Html.Action("Create", "Comment", new { id = Model.PostId })</p> <!--**********This is the line that is important-->
#*#=Html.RenderAction("Create", "Comments", new { postId = Model.PostId });*#
#*#Html.Partial("Comments")*#
</div>
</div>
<p>
#*#Html.ActionLink("Add a Comment", "Create", "Comment")*#
#Html.ActionLink("Comment", "Create", "Comment", new { id = Model.PostId }, null) |
#Html.ActionLink("Back to List", "Index")
The Comment/Create Razor HTML file that is getting pulled in by the Html.Action:
#model FantaC.Models.Comment
#{
Layout = null;
}
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Comment</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CommentSubject, htmlAttributes: new { #class = "control-label col-md-10 displayBlock" })
<div class="col-md-12">
#Html.EditorFor(model => model.CommentSubject, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CommentSubject, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CommentContent, htmlAttributes: new { #class = "control-label col-md-10 displayBlock" })
<div class="col-md-12">
#Html.EditorFor(model => model.CommentContent, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CommentContent, "", 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>*#
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
The important section from the CommentController:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(string id, [Bind(Include = "CommentSubject,CommentContent")] Comment model)
{
if (ModelState.IsValid)
{
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
var commentId = (23817 + db.Comment.Count()).ToString().PadLeft(10, '0');
var comment = new Comment
{
CommentId = commentId,
PostId = id,
UserName = user.UserName,
PostTime = DateTime.Now,
CommentSubject = model.CommentSubject,
CommentContent = model.CommentContent
};
db.Comment.Add(comment);
db.SaveChanges();
return View("Details/" + id, "Post");
}
return View(model);
}
I also tried return View("../post/details/" + id); to no avail. How can I get back up to the post view url (post/details/{id} from the CommentController?
As a side note, I had it almost working by taking out the returns and making the method void, but after clicking the submit comment button the whole comment/create form would disappear. I would be fine going back to that way of doing things if anyone knows a way to make the form stay after clicking the create comment button.
Thanks for any help! :)
Edit:
I forgot to mention that I tried this too. It returns an error that looks like this:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Child actions are not allowed to perform redirect actions.
Source Error:
Line 32: }
Line 33:
Line 34: #Html.Action("Create", "Comment", new { id = Model.PostId })
Line 35:
You should follow the PRG (POST-REDIRECT-GET) pattern. After saving the comment, you should redirect to the post details page.
You may use the RedirectToAction method to return a RedirectResponse back to the browser which will make a new GET request to the post details action method.
So replace
return View("Details/" + id, "Post");
with
return RedirectToAction("Details" , "Post", new {id=id});

Data is not passing into SQL Server when using MVC Partial view

I have a popup dialog inside the partial view. When a user clicks "Create" button, a popup dialog is shown, inside the popup dialog is a form where user types information and the information is then save into the database. I got everything working and didn't get any errors but the data I typed didn't get saved into the database.
Please help, I am new to programming, Thank you.
Index page:
<li>#Html.Partial("_Create")</li>
In my _Create partial view, I scaffolded the partial view using the Create template
#model test.Models.Question
<li>Create</li>
<div class="dialog-form-create-question" title="Create a question">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Title, htmlAttributes: new { #class = "control-label col-md-1" })
<div class="col-md-11">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-8">
<input type="submit" value="Submit" class="btn btn-primary"/>
</div>
</div>
</div>
}
</div>
My JQuery scripts for the form dialog nested inside the partial view:
$(document).ready(function () {
$(".dialog-form-create-question").dialog({
autoOpen: false,
height: 510,
width: 800,
modal: true,
draggable: false,
resizable: false
});
$('.create-question').click(function () {
$('.dialog-form-create-question').dialog("open");
});
$('.cancel-button').click(function () {
$('.dialog-form-create-question').dialog("close");
});
});
In my Home controller, I changed the ActionResult Create(from scaffolding) to _Create:
// GET: Home/Create
public ActionResult _Create()
{
return View();
}
// POST: Home/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult _Create([Bind(Include = "Id,Title")] Question question)
{
if (ModelState.IsValid)
{
db.Questions.Add(question);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(question);
}
please try changing
#using (Html.BeginForm())
{
}
to
#using (Html.BeginForm("_Create","Home",FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Title, htmlAttributes: new { #class = "control-label col-md-1" })
<div class="col-md-11">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
<input type="submit" value="submit"/>
</div>
</div>
</div>
}
and see that your debugger strikes to _Create (post) method in your home controller with the values

Categories

Resources