ASP.net MVC - how does controller action method gets parameter value? - asp.net-mvc

I know the title of this question isn't very pretty. I dint have a better way to put it.
Lets look at the following code :
View for delete action:
#model LearningMVC.Models.Blog
#{
ViewBag.Title = "Delete";
}
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>Blog</legend>
<div class="display-label">
#Html.DisplayNameFor(model => model.URL)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.URL)
</div>
</fieldset>
#using (Html.BeginForm()) {
<p>
<input type="submit" value="Delete" /> |
#Html.ActionLink("Back to List", "Index")
</p>
}
Controller action for delete action
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Blog blog = db.Blogs.Find(id);
db.Blogs.Remove(blog);
db.SaveChanges();
return RedirectToAction("Index");
}
My questions is, How on earth this method got its parameter ?!

Related

Form submit using partail View error

I have created a form for add comment. I have created it in main View called Index in Home controller. bellow is Index View
private projectDBEntities db = new projectDBEntities();
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult AddComment()
{
return PartialView("_Comment");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddComment(comment cmt)
{
if (ModelState.IsValid)
{
db.comments.Add(cmt);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return PartialView("_Comment", cmt);
}
below is _Comment Partial View
#using (Html.BeginForm()) {#Html.AntiForgeryToken()#Html.ValidationSummary(true)
<fieldset>
<legend>comment</legend>
<div class="editor-label">
#Html.LabelFor(model => model.cmd_content)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.cmd_content)
#Html.ValidationMessageFor(model => model.cmd_content)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.t_email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.t_email)
#Html.ValidationMessageFor(model => model.t_email)
</div>
<p>
<input type="submit" value="Comment" />
</p>
</fieldset>}
System.Web.HttpException was occuerd. I want to know What is the reason behind this error and what is the best method to form submit using partail View.
Id have to agree with Sandip's answer here, but to elaborate ..
#using (Html.BeginForm("AddComment", "Home"))
{
//Content to send to the server-side
}
As long as your model in your partial view points to your 'Comment' object, then this should work fine when using #Html.EditorFor(). In your controller, your already waiting for your 'Comment' object to be populated. So on Post, when the submit is clicked, it will populate that object.
Hope this helps.
#using (Html.BeginForm("AddComment", "Home"))
{
}

connecting an action of button in view in asp.net mvc3

I am beginner in asp.net mvc . I am going to connect an action of button in view.
but i cant. i work with web form, in fact i want to click on the button, create action will be called and insert the data.
my code is as following:
The Controller:
namespace BookStore.Controllers
{
public class BookController : Controller
{
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(book bookobj)
{
var dBook=new DBook();
dBook.Insertbook(bookobj);
return RedirectToAction("Index", "Home");
}
}
}
The View:
#model BookStore.Models.DomainObject.book
#{
ViewBag.Title = "Create";
}
<h2>insert data/h2>
#using(Html.BeginForm())
{
#Html.ValidationSummary(true);
<fieldset>
<div>
#Html.LabelFor(model=> model.book_name)
</div>
<div>
#Html.EditorFor(model => model.book_name)
</div>
<div>
#Html.LabelFor(model=>model.book_qty)
</div>
<div>
#Html.EditorFor(model=>model.book_qty)
</div>
<br/>
<div>
<input id="Button_craete_book" type="button" value="insert" />
</div>
</fieldset>
}
Change the button type to "submit":
<input id="Button_craete_book" type="submit" value="insert" />
That will post the form and values to the Edit method in the controller, as marked with the HttpPost attribute.

How to show data from two different tables in one 1 view

I'm creating a forum where user can ask questions and comment on it ....using mvc3
Inside that i have a link "details" for each question .... in side that i have 2 more links "show" and "add comments"
in show one can see all comments related to a particular Question
and in Add comments we can add a comment for particular question
its controller code is as follow:
public ActionResult Addnew(int id)
{
return View();
}
[HttpPost]
public ActionResult Addnew(Answer answr, int id)
{
answr.QuestionQId = id;
_db.Answers.Add(answr);
_db.SaveChanges();
return RedirectToAction("Index");
}
and in view i have written:
#model Hobby.Models.Answer
#{
ViewBag.Title = "Addnew";
}
<h2>Addnew</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>Answer</legend>
<div class="display-label">Question</div>
<div class="display-field">
#Html.DisplayFor(model => model.Question.Que)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Ans)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Ans)
#Html.ValidationMessageFor(model => model.Ans)
</div>
<p>
<input type="submit" value="Add Comment" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
but it is not showing the Question from question table.....
Please help me
I don't see where you are binding the necessary data I think AddNew [Get] method should get the question from DB and set it to the view, I suppose you should do something similar to this
public ActionResult Addnew(int id)
{
Answer ans = new Answer();
ans.Question = _db.Questions.SingleOrDefault(q => q.Id == id);
return View(ans);
}
#Jayanga is right but I think you still wanted to show data from "2 tables" as you stated in the title of your question. Assuming you mean that you want to show the question and all related answers, and also assuming that this is .NET Entity Framework (don't know by heart the syntax of Linq2Sql), you would do:
public ActionResult Addnew(int id)
{
var question = _db.Questions.Include("Answers").SingleOrDefault(q => q.Id == id);
return View(question);
}
This changes your binding model type to Question, but I'm assuming here that a Question can have more than 1 answer, and in that case, you'll have in your View all the information you need... something like this:
// In your .cshtml file
<article class="question">#Model.Que</article> #* this is your question text *#
#foreach (var answer in Model.Answers.OrderBy(a => a.PostedDate)) { #* assuming you want to sort this *#
<article class="answer">#answer.Ans</article> #* this would be your answer text *#
}

Asp.net mvc delete with AcceptVerbs HttpVerbs.Post method auto invoke problem

I'm new to Asp.net MVC.
I have an application that manages users. My problem is that when I click on a delete link of a user row, the delete method has [AcceptVerbs(HttpVerbs.Post)] annotation is called automatically after a render delete method invoked. Thus, the user with id is deleted before I click on the delete confirm button and the error has occurred afterward.
Everything worked fine before. So, I don't know why this happend.
My code:
// GET: /User/Delete/5
[Authorize]
public ActionResult Delete(int id)
{
return View(GetByUserId(id));
}
// POST: /User/Delete/5
[Authorize]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(Users user)
{
//some process
}
The second method invokes automatically after the first one is called.
The view:
<h2>Delete</h2>
<p class="error"><%= Html.Encode(ViewData["messages"]) %></p>
<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>Fields</legend>
<div class="display-label">UserId</div>
<div class="display-field"><%= Html.Encode(Model.UserId) %></div>
<div class="display-label">UserName</div>
<div class="display-field"><%= Html.Encode(Model.UserName) %></div>
<div class="display-label">FullName</div>
<div class="display-field"><%= Html.Encode(Model.FullName) %></div>
<div class="display-label">Email</div>
<div class="display-field"><%= Html.Encode(Model.Email) %></div>
<div class="display-label">DayOfBirth</div>
<div class="display-field"><%= Html.Encode(String.Format("{0:MM/dd/yyyy}", Model.DayOfBirth))%></div>
<div class="display-label">Phone</div>
<div class="display-field"><%= Html.Encode(Model.Phone) %></div>
<div class="display-label">Active</div>
<div class="display-field"><%= Html.Encode(Model.Active) %></div>
</fieldset>
<% using (Html.BeginForm()) { %>
<p>
<input type="submit" value="Delete" /> |
<%= Html.ActionLink("Back to List", "Index") %>
</p>
<% } %>
You can create another view which will solve your purpose of confirmation delete.
Please find more details using following link.
http://forums.asp.net/t/1513258.aspx
Please find your modify code below.
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
public ActionResult Delete()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(RegisterModel ob)
{
return RedirectToAction("Index");
}
}
Index.cshtml
#{
ViewBag.Title = "Home Page";
}
<h2>#ViewBag.Message</h2>
<h1>
#Convert.ToString(ViewBag.Delete)
</h1>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">
http://asp.net/mvc</a>.
<br />
<br />
#Html.ActionLink("Delete record", "Delete");
<br />
<br />
</p>
delete.cshtml
#model MvcApplication1.Models.RegisterModel
#{
ViewBag.Title = "Delete";
}
<h2>
Delete</h2>
<div>
Are you sure you want to delete this?</div>
#using (Html.BeginForm())
{
<p>
<input type="submit" value="Delete" />
|
</p>
}
Above code is same as your code and it's working fine. Please have a look.

keeping Object Data after passing it to a strongly typed view

I have a simple ASP.NET MVC 3 site, from my Controller out of the Edit Action I pass a Object (a class which is also mapped by nhibernate)
After editing and clicking save i pass it to the [HTTPPost] decoraded Method but and all properties are correct, excerpt the "id" property it hat a guid value equivalent to NULL (00000000-0000-000...).
Is there a problem using the Domain Model to strongly type my Views? May the problem be that Id has:
{get; private set;}
???
Thanks in advance.
Here The Code:
My View:
'#model fnh.DataModel.Kunde
#{
View.Title = "EditKunde";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>EditKunde</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Fields</legend>
#Html.EditorFor(model => model._id)
#Html.EditorFor(model => model._KdNr);
<div class="editor-label">
#Html.LabelFor(model => model._Name)
`enter code here` </div>
<div class="editor-field">
#Html.EditorFor(model => model._Name)
#Html.ValidationMessageFor(model => model._Name)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
'
My Controller Actions:
' public ActionResult EditKunde(Guid id)
{
return View(_kunden.GetKundeById(id));
}
[HttpPost]
public ActionResult EditKunde(Kunde kunde)
{
Ansprechpartner anp = new Ansprechpartner();
anp._Name = "JustATry";
kunde._Ansprechpartner.Add(anp);
`enter code here` _kunden.EditKunde(kunde);
return View();
}'
Are you adding the Id property to your form (maybe as a hidden field)?
It would be useful if you post the Action code (for both Edit Actions), and the View.

Resources