MVC tabs saving partialview - asp.net-mvc

I am using partialviews in each tab. I have 3 tabs.
After I have selected a tab, how to submit a form in a partialview and have it stay on the same tab after posting to controller? I just want to refresh the partialview after saving and hopefully not the whole page.
order controller
public ActionResult order()
{
return View();
}
order.cshtml
<div id="tabs">
<ul class="nav nav-tabs">
<li class="active">General</li>
<li>Item</li>
<li>Total</li>
</ul>
<div id="tabs-1">
#{Html.RenderPartial("_Partial_General_Tab");}
</div>
<div id="tabs-2">
#{Html.RenderPartial("_Partial_Item_Tab");}
</div>
<div id="tabs-3">
Content for Tab 3 goes here.<br />
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#tabs").tabs();
});
</script>
_Partial_General_Tab.cshtml
#model Mvc5.Models.ORDERMetadata
#using (Html.BeginForm("Edit", "Order"))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
// Set New Order Number
#Html.HiddenFor(model => model.Order_Number, new { #Value = ordernumber })
#Html.TextBoxFor(model => model.Order_Date})
<button id="editorder" type="submit">Save</button>
}
_Partial_Item_Tab.cshtml
#model Mvc5.Models.ORDER_DETAILSMetadata
#using (Html.BeginForm("Item", "Order"))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
// Set New Order Number
#Html.HiddenFor(model => model.Order_Number, new { #Value = ordernumber })
#Html.TextBoxFor(model => model.Item})
<button id="edititem" type="submit">Save</button>
}
Edit Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ORDERMetadata model)
{
try
{
// update order
return RedirectToAction("order"); //<----- Is this correct redirecting?????
}
}
Item Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Item(ORDER_DETAILSMetadata model)
{
try
{
// update order
return RedirectToAction("order"); //<----- Is this correct redirecting, do I need to pass what tab it is on?????
}
}

instead of using Html.BeginForm use Html.AjaxForm

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"))
{
}

Pass object to partial view

I have this controller which fetches an object that I would like to render in a partial view:
public ActionResult EditPhoto(string id)
{
var photo = RavenSession.Load<ContentPage>(id);
return View("_editPhoto");
}
Its the photo I would like to pass to my partial view.
I have this in my view:
#{
Html.RenderPartial("_editPhoto" );
}
How will I go about to pass my photo into the partial view in order for it to render in its parent?
EDIT:
This is how I pass the object to the controller:
#foreach (var item in Model.Photographys)
{
<li class="span3" style="text-align: center">
<div class="thumbnail thumbnail-1">
#Html.ActionLink(item.Name,
"EditPhoto", // <-- ActionMethod
new { id = item.Id }, // <-- Route arguments.
null // <-- htmlArguments .. which are none. You need this value
// otherwise you call the WRONG method ...
// (refer to comments, below).
)
<h3 style="margin-bottom: 10px;">#item.Name</h3>
<div class="">
<div class="">
<img src="#item.ImgUrl" alt="" style="visibility: visible; opacity: 1;">
</div>
</div>
<section>
<p>#item.Description</p>
Read More
<p>#item.IsAccordion</p>
</section>
</div>
</li>
}
There seems a problem with this line however:
#{
Html.RenderPartial("_editPhoto" , Model);
}
Model gets underlined explaining that the Model passed into it (Photo) is not the right one..It seems that _editPhoto inherits the same Model as its parent maybe?
I managed to do this in the view:
#{
var i = new Photography();
Html.RenderPartial("_editPhoto", i);
}
The problem now is that the partialView gets rendered in a new window and not in its parent as I want it to.
UPDATE
Im gonna give this one last go, wont create a new question:
This is my controller passing a photo to a partial view:
public ActionResult EditPhoto(string id)
{
var photo = RavenSession.Load<ContentPage>(id) as Photography;
return PartialView("_editPhoto", photo);
}
My "mainview" contains this code to render the partial view with the photo getting sent to it:
<div class="form-control">
#{
var model = new Photography();
Html.Partial("_editPhoto",model);
}
</div>
This opens up a new window where my new photo shows up. I would like it to get rendered inside of its parents view the same way as it gets rendered automaticaly when i first visit the page...
Your controller action method should be:
public ActionResult EditPhoto(string id)
{
var photo = RavenSession.Load<ContentPage>(id);
return View("EditPhoto",photo);
}
and your "EditPhoto" view should be:
#{ Html.RenderPartial("_editPhoto",Model); }
Update
Your controller action method should be:
public ActionResult Photos()
{
return View();
}
public ActionResult EditPhoto(string id)
{
var photo = RavenSession.Load<ContentPage>(id);
return View(photo);
}
your "EditPhoto" should be view (not a partialview), on link click, "EditPhoto" action method is called and it returns the "EditPhoto" view
This questions seems related to one of your previous question.
Controller should be as follows;
public ActionResult EditPhoto(string id)
{
var photo = RavenSession.Load<ContentPage>(id);
return PartialView("_editPhoto", photo);
}
In your partial view _editPhoto, you can have the following code. I assume photo variable is a Photography object.
#model aPhoto_web.Models.AdminPages.Photography
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Photography</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>
}
Thanks!

Create new parent and child on the same page

My MVC application has a classic parent-child (master-detail) relations.
I want to have a single page that create both the new parent and the children on the same page. I have added an action the returns a partial view that and adds the child HTML to the parent’s view, but I don’t know how to associate the newly created child in the action to the original parent (in other word, how to I add the new child entity to the collection of these entities in the parent entity).
I guess that when I submit the form the action should get the parent entity with the newly created children in its collection.
So to make things short, what should be the code of the action that creates the child entity and how is the child added to its parent collection?
I have read a lot of posts here (and other sites) and couldn’t find an example.
The application uses MVC 4 and Entity Framework 5.
Code sample (I removed some of the code the keep it simple).
The model is Form (parent) and FormField (child) entities.
public partial class Form
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<FormField> FormFields { get; set; }
}
public partial class FormField
{
public int ID { get; set; }
public string Name { get; set; }
public int FormID { get; set; }
}
The following partial view (_CreateFormField.cshtml) creates new FormField (child).
#model FormField
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>FormField</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.FormID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FormID)
#Html.ValidationMessageFor(model => model.FormID)
</div>
</fieldset>
}
And the following view (Create.cshtml) is the one the creates the Form.
#model Form
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>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>
#Html.ActionLink(
"Add Field",
"CreateFormField",
new { id = -1},
new { #class = "form-field" })
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<div id="CreateFormField"></div>
#section Scripts {
<script>
$(function () {
$('.form-field').on('click', function (e) {
$.get($(this).prop('href'), function (response) {
$('#CreateFormField').append(response)
});
e.preventDefault();
});
});
</script>
#Scripts.Render("~/bundles/jqueryval")
}
The following actions handle the creation in the FormController.
[HttpPost]
public ActionResult Create(Form form)
{
if (ModelState.IsValid)
{
db.Forms.Add(form);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(form);
}
public ActionResult CreateFormField(string id = null)
{
// I guess something is missing here.
return PartialView("_CreateFormField", new FormField());
}
Thanks in advance,
Sharon.
I think the best and simplest way for you is that you have a view for creating Form and at the bottom of it put a fieldset to assign FormFields to it.
For the fieldset, you should have two partial views: One for create and another for edit. The partial view for creating should be something like this:
#model myPrj.Models.Form_FormFieldInfo
#{
var index = Guid.NewGuid().ToString();
string ln = (string)ViewBag.ListName;
string hn = ln + ".Index";
}
<tr>
<td>
<input type="hidden" name="#hn" value="#index" />
#Html.LabelFor(model => model.FormFieldID)
</td>
<td>
#Html.DropDownList(ln + "[" + index + "].FormFieldID",
new SelectList(new myPrj.Models.DbContext().FormFields, "ID", "FieldName"))
</td>
<td>
<input type="button" onclick="$(this).parent().parent().remove();"
value="Remove" />
</td>
</tr>
By calling this partial view in the create place view ajaxly, you can render some elements for each tag. Each line of elements contains a label, a DropDownList containing tags, and a remove button to simply remove the created elements.
In the create place view, you have a bare table which will contain those elements you create through the partial view:
<fieldset>
<legend>Form and FormFields</legend>
#Html.ValidationMessageFor(model => model.FormFields)</label>
<table id="tblFields"></table>
<input type="button" id="btnAddTag" value="Add new Field"/>
<img id="imgSpinnerl" src="~/Images/indicator-blue.gif" style="display:none;" />
</fieldset>
and you have the following script to create a line of elements for each tag:
$(document).ready(function () {
$("#btnAddField").click(function () {
$.ajax({
url: "/Controller/GetFormFieldRow/FormFields",
type: 'GET', dataType: 'json',
success: function (data, textStatus, jqXHR) {
$("#tblFields").append(jqXHR.responseText);
},
error: function (jqXHR, textStatus, errorThrown) {
$("#tblFields").append(jqXHR.responseText);
},
beforeSend: function () { $("#imgSpinnerl").show(); },
complete: function () { $("#imgSpinnerl").hide(); }
});
});
});
The action method GetFormFieldRow is like the following:
public PartialViewResult GetFormFieldRow(string id = "")
{
ViewBag.ListName = id;
return PartialView("_FormFieldPartial");
}
and your done for the create... The whole solution for your question has many codes for views, partial views, controllers, ajax calls and model binding. I tried to just show you the way because I really can't to post all of them in this answer.
Here is the full info and how-to.
Hope that this answer be useful and lead the way for you.
You can use #Html.RenderPartial(_CreateFormField.cshtml) htlper method inside your parent cshtml page.
For mode info, http://msdn.microsoft.com/en-us/library/dd492962(v=vs.118).aspx
I am providing an pseudo code example,
#Foreach(childModel in model.FormFields)
{
#Html.RenderPartial("childView.cshtml","Name", childModel)
}
Please try it in proper c# syntactical way and you will get your partial views rendered for each collection item.
The problem is that your partial view needs to use:
#model Form //Instead of FormField
and then inside of the partial view you must use model => model.FormField.x
<div class="editor-label">
#Html.LabelFor(model => model.FormField.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FormField.Name)
#Html.ValidationMessageFor(model => model.FormField.Name)
</div>
This only works for one-to-one relationships (or so I read in this thread: Here). It also does not matter if you have #Html.Form inside of the partial view.
After making those changes I had no problem getting all of the posted data back to the controller.
EDIT: I've run into problems with this as anyone would soon figure out.
The better way to do this (that I've seen) is instead use an EditorTemplate. This way the editor stays independent of the Parent, and you can add a Form on any page, not simply a page where you are also adding a FormField.
You would then replace
#Html.Partial("view")
with
#Html.EditorFor()
Basically, I've found out that it's far better to use an #Html.EditorFor instead of a partial view when doing editing (It is called a view - not an editor).
If you want to use grid based layout you may want to try Kendo UI grid
Use jQueryto add FormField on click of button.
Similar I've used it as follows
<div class="accomp-multi-field-wrapper">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>FormId</th>
<th>Remove</th>
</tr>
</thead>
<tbody class="accomp-multi-fields">
<tr class="multi-field">
<td> <input name="FormFields[0].Name" type="text" value=""></td>
<td> <input name="FormFields[0].FormId" type="text" value=""></td>
<td> <button type="button" class="remove-field">X</button></td>
</tr>
</tbody>
<tr>
<th><button type="button" class="add-field btn btn-xs btn-primary addclr"><i class="fa fa-plus"></i> Add field</button> </th>
</tr>
</table>
</div>
and jQuery is as follows for adding field and removing
<script>
$('.accomp-multi-field-wrapper').each(function () {
var $wrapper = $('.accomp-multi-fields', this);
$(".add-field", $(this)).click(function (e) {
var $len = $('.multi-field', $wrapper).length;
$('.multi-field:first-child', $wrapper).clone(false, true).appendTo($wrapper).find('select,input,span').val('').each(function () {
$(this).attr('name', $(this).attr('name').replace('\[0\]', '\[' + $len + '\]'));
});
$(document).on("click",'.multi-field .remove-field', function () {
if ($('.multi-field', $wrapper).length > 1) {
$(this).closest('tr').remove();
//
$('.multi-field', $wrapper).each(function (indx) {
$(this).find('input,select,span').each(function () {
$(this).attr('name', $(this).attr('name').replace(/\d+/g, indx));
})
})
}
});
</script>
Hope so this is going to help you.

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 do I call submit in mvc app?

I have mvc3 web app.
inside that I have one Enquiry form once I submit that form it should save all data into database for that I have used Entity Framework.
EnquiryController.cs
public class EnquiryController : Controller
{
aspnetdbEntities dbEntities = new aspnetdbEntities();
//
// GET: /Enquiry/
public ActionResult Index()
{
return View();
}
//
// GET: /Enquiry/
public ActionResult Enquiry()
{
return View();
}
//
//POST: /Enquiry/
[HttpPost]
public ActionResult Enquiry(Enquiry enquiry)
{
if (ModelState.IsValid)
{
dbEntities.Enquiries.AddObject(enquiry);
dbEntities.SaveChanges();
return RedirectToAction("Index");
}
return View(enquiry);
}
}
Enquiry.cshtml
#model MyWeb.Models.Enquiry
#{
ViewBag.Title = "Enquiry";
}
<h2>Enquiry</h2>
<div>
<fieldset>
<legend>Enquiry Form</legend>
<div class="editor-label">
#Html.LabelFor(m => m.FirstName)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.FirstName)
#Html.ValidationMessageFor(m => m.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.LastName)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.LastName)
#Html.ValidationMessageFor(m => m.LastName)
</div>
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
</div>
But when I clicked on Submit button it is not working no round rip no refresh
please help me where i go wrong i'm newbie.
ashuthinks,
just add the htmlHelper (for forms) to your view:
#using(Html.BeginForm()){
// exisiting fieldset stuff
<fieldset>... bla</fieldset>
}
around your fieldset and you're good to go

Resources