MVC partial view controller not running on load - c#

Im trying to load a MVC partial view in to a modal popup. The popup contains a drop down list which I am trying to populate on the ActionResult that loads when the view is loaded. The problem is the controller code isn't getting ran.
My code is as follows -
View:
<div id="modal_form_horizontal_addnote" class="modal fade">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal">×</button>
<h5 class="modal-title">Add Note</h5>
</div>
#Html.Partial("AddNote", new IHD.Core.Models.CreateTicketNoteModel { TicketHeaderId = Model.Id })
</div>
</div>
The partial view:
#model IHD.Core.Models.CreateTicketNoteModel
#using (Html.BeginForm("AddNote", "Ticket", FormMethod.Post))
{
#Html.HiddenFor(model => model.TicketHeaderId)
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-12">
<div class="tab-content">
<div class="tab-pane active" id="highlighted-justified-tab1">
<div class="form-group">
#Html.LabelFor(model => model.WorkType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-12">
#Html.DropDownListFor(model => model.WorkType, new SelectList(Model.WorkTypeOptions, "Key", "Value", Model.WorkType), new { #name = "select", #class = "form-control" })
#Html.ValidationMessageFor(model => model.WorkType, "", new { #class = "text-danger" })
</div>
</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>
</div>
}
The controller:
public ActionResult AddNotePhase(int id = 0, int taskId = 0)
{
CreateTicketPhaseNoteModel note = new CreateTicketPhaseNoteModel();
note.TicketHeaderId = id;
// Populate the work type dropdown list
note.WorkTypeOptions.Add("", "-- Select a Work Type --");
note.WorkTypes = _workTypeService.GetAll().ToList();
foreach (var c in note.WorkTypes)
{
note.WorkTypeOptions.Add(c.Id.ToString(), c.Description);
}
//note.PhaseTask = taskId;
return PartialView(note);
}

You controller code isn't being hit because you are passing a model to the partial view and not calling the action. You need to use #{Html.RenderAction();} instead to call your action with the appropriate values.

Related

MVC Razor form button not calling controller specified

So within my view, I have:
<div id="createProductModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Create Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#using (Html.BeginForm("Create", "Product", FormMethod.Post, new { id = "createProductForm", #class = "form-horizontal"}))
{
<div class="form-group">
<div class="col-md-4">
#Html.LabelFor(m => Model.Product.Name, new { #class = "control-label" })
</div>
<div class="col-sm-8">
#Html.TextBoxFor(m => Model.Product.Name, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-4">
#Html.LabelFor(m => Model.Product.IsActive, new { #class = "control-label" })
</div>
<div class="col-sm-8">
#Html.CheckBoxFor(m => Model.Product.IsActive, new { #class = "form-control" })
</div>
</div>
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal" onclick="$('#createProductForm').submit();">Add product</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
And then in my ProductsController I have added an action like so:
[HttpPost]
public ActionResult Create(Product product)
{
return View();
}
But for some reason when clicking submit it redirects me to this URL:
http://localhost/Product/Create
And throws a 404 error like so:
The resource cannot be found.
I've not defined a route within the route configs surely this shouldn't matter?
Does anyone understand what i seem to be doing wrong?
Second parameter of Html.BeginForm is the controller name. Given that you have a ProductsController, instead of
Html.BeginForm("Create", "Product", ...
Try
Html.BeginForm("Create", "Products"
Check FormExtensions.BeginForm

Submitting a form from a partial view

I'm trying to submit a form from a modal generated in a partial view. And I don't know how to get back the submitted form.
Here is the view:
#model Myproject.ViewModels.GetMonitorFromDeviceViewModel
#{
ViewBag.Title = "GetMonitorFromDevice";
Layout = "~/Views/Shared/ManagementPage.cshtml";
}
<div id="Accordion">
#{
foreach (var type in Model.AvailableTypesAvailableMonitors)
{
<div class="card">
<div class="card-header">
<a class="card-link" data-toggle="collapse" data-parent="#accordion" href="##type">
#type
</a>
</div>
<div id="#type" class="collapse show">
<div class="card-body">
#{
foreach (var monitor in Model.ActiveMonitors)
{
if (monitor.Type == #type)
{
<p>
#monitor.Name
<span class="btn btn-xs btn-primary btnEdit" onclick="createModal('#Url.Action("NameMonitor", "DeviceManager" , new { idDevice = monitor.DeviceOwner.ID, monitorName = monitor.Name })')">Details</span>
</p>
}
}
}
</div>
</div>
</div>
}
}
</div>
And here is my modal at the bottom of the page:
<div class="modal fade" id="myModal" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content" id="modelContent">
</div>
</div>
</div>
<script>
function createModal(url) {
$('#modelContent').load(url);
$('#myModal').modal('show');
}
</script>
And finally, here is my partial view that is displayed as a modal:
#model MyProject.ViewModels.NameMonitorModal
#using (Html.BeginForm("NameMonitor", "DeviceManager", FormMethod.Post))
{
<div class="modal-body">
<div class="form-group">
#Html.LabelFor(model => model.NewName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NewName, new { htmlAttributes = new { #class = "form-control", #Value = Model.TrueName } })
#Html.ValidationMessageFor(model => model.NewName, "", new { #class = "text-danger" })
</div>
</div>
#Html.HiddenFor(model => model.TrueName)
#Html.HiddenFor(model => model.IdDevice)
</div>
<div class="modal-footer">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save name" class="btn btn-default" data-dismiss="modal" />
</div>
</div>
</div>
}
In my controller, I have an action for my partial view called ActionResult NameMonitor.
In order to catch the submited form, I tried to add another action with the [HttpPost] tag with the same name but doesn't work. I also tried to use the main page action with the [HttpPost] tag but it doesn't work either. As you can see, I have specified the action and controller in the form itself but its still not working.
Now, I'm a little bit out of idea of how I can get the information from my modal back.
data-dismiss="modal" will close the modal without submitting the form, see Dismiss and submit form Bootstrap 3
You can change the submit button to call a JavaScript function to submit the form, then close the modal.
function submitModal() {
$('#myFormId').submit();
$('#myModal').modal('hide');
}

Popup partial view in a bootstrap model popup

#Html.ActionLink("edit", "Edit", "MedQuantityType", new { id = item.Med_quan_typeId }, new
{
#* Needed to link to the html of the modal*#
data_target = "#mymodel",
#* Tells the bootstrap javascript to do its thing*#
data_toggle = "modal",
})
This the action link I try to popup partial view in bootstrap model, it's working fine when I try to edit & save it works except model state is not valid
here my controller code
public async Task<ActionResult > Edit([Bind(Include = "Med_quan_typeId,Med_quan_type,Med_quantity")] Med_quantity_type med_quantity_type)
{
if (ModelState.IsValid)
{
db.Entry(med_quantity_type).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return PartialView(med_quantity_type);
}
If my model state fails the controller return partial view but its not popup in mymodel this is my partial view cshtml page
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Medicine Quantity Type - Edit</h4>
</div>
<div class="modal-body">
#using (Ajax.BeginForm("Edit", "MedQuantityType",
new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "mymodel"
}))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.Med_quan_typeId)
<div class="form-group">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.Med_quan_type, new { #class = "control-label " })
</div>
<div class="col-md-6">
#Html.TextBoxFor(model => model.Med_quan_type, new { #class = "form-control", #id = "txtquantype" })
#Html.ValidationMessageFor(model => model.Med_quan_type)
</div>
</div>
<div class="form-group">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.Med_quantity, new { #class = "control-label" })
</div>
<div class="col-md-6">
#Html.TextBoxFor(model => model.Med_quantity, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Med_quantity)
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" value="Save" class="btn btn-success" id="btnsubmit" />
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
<div ID ="popupform"class="popover">
<div class="alert-danger"> Please Fix The errors </div>
</div>
}
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$(function () {
debugger;
// when the modal is closed
$('#mymodel').on('hidden.bs.modal', function () {
// remove the bs.modal data attribute from it
$(this).removeData('bs.modal');
// and empty the modal-content element
$('#mymodel .modal-content').empty();
});
});
});
</script >
Please help anyone how to popup partial view, once controller return partial view
From Task<ActionResult > to Task<PartialViewResult> then change your ActionLink to RenderPartial.
It should work fine.
Change the return type of your action to Task<PartialView>

how to do a create partial view inside a edit view?

I can add a create partial view within a modal bootstrap so that it can add value in the table with a edit view of the field value ?
My create partial view
#model MVCLayout.Models.Table2
<p>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="form-group">
#Html.Label("Cargo: ", new { style = "width:160px" })
#Html.TextBoxFor(model => model.ID, new { style = "width:200px" })
</div>
<br/>
<div class="form-group">
#Html.Label("Percentual: ", new { style = "width:160px" })
#Html.TextBoxFor(model => model.Name, new { style = "width:200px" })
</div>
<br/>
<div class="form-group">
#Html.Label("Serviço: ", new { style = "width:160px" })
#Html.TextBoxFor(model => model.Work, new { style = "width:200px" })
</div>
<br/>
<p>
<input type="submit" value="Save" />
</p>
}
</p>
My Edit View
<html>
<body>
#model MVCLayout.Models.Table1
#{
ViewBag.Title = "Edit";
}
<div id="signup">
<div class="rontainer">
<div class="header">
<div id="dock">
<br>
#using (Html.BeginForm("Edit", "AdmServicos", FormMethod.Post, new { #class = "form-inline" }))
{
#Html.AntiForgeryToken()
<fieldset>
<legend>Editar Servios</legend>
<br>
<div class="form-group">
#Html.Label("Código:", new { style = "width:160px" })
#Html.TextBoxFor(model => model.ID, new { style = "width:55px", #readonly = "readonly" })
<div class="form-group">
#Html.Label("Descrição: ", new { style = "width:160px" })
#Html.TextBoxFor(model => model.Descricao, new { style = "width:550px", #readonly = "readonly" })
</div>
</div>
<br />
<br /><br />
<p>
<input type="submit" value="Salvar" />
</p>
</fieldset>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
#{
Html.RenderPartial("CreateTable2", Model.ID);
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
}
</div>
</div>
</div>
</body>
</html>
Can I do this with a partial view or the best way to do this?
create a property of Table2 type in your Table1 Model like below :
public class Table1
{
public Table2 table2 {get; set;}
//other properties of Table1 Model
}
Now in your Edit View:
<div class="modal-body">
#{
Html.RenderPartial("CreateTable2", Model.table2);
}
</div>
Now in your Action of the Controller :
public ActionResult Edit(Table1 model)
{
var editPartialViewData = model.table2;
// Do whatever you want to do with this data
}

MVC model binding, Initial Model Missing

In this instance I have two pages, in the post method of the first I return the view/viewmodel of the second like so :
[HTTPPost]
public Task<ActionResult> Page1(Page1Model model)
{
var Page2Model = GrabDataMethod(model);
return View("Page2", Page2Model); //Point 1
}
[HTTPPost]
public Task<ActionResult> Page2(Page2Model model //Point 2)
{
var updatedModel= RunFiltersMethod(model)
return View(updatedModel);
}
Now, in this case Page2 renders properly from (Point 1) with all values passed in above from the GrabDataMethod. However, when I POST for Page2 the Page2Model I receive at (Point 2) has none of the original entries, e.g. everything not modified directly by Page2 itself is null or default (in fact it seems the model from the post method is a new model entirely). I've made a horrible workaround for the time being, but I need a proper fix, is there any reason that this would be happening?
Page2 View Code
#model Mvc2013.Models.Page2Model
#using (Html.BeginForm("Page2", "Controller"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
<div class="row">
<div class="col-md-12">
#Html.Kendo().Chart(<!-- code removed, this is working -->)
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="col-md-8">
#Html.LabelFor(model => model.Prop1, new { #class = "control-label" })
</div>
<div class="col-md-4">
#Html.EditorFor(model => model.Prop1, new { #class = "control-label" })
#Html.ValidationMessageFor(model => model.Prop1)
</div>
</div>
<div class="col-md-3">
<div class="col-md-8">
#Html.LabelFor(model => model.Prop2, new { #class = "control-label" })
</div>
<div class="col-md-4">
#Html.EditorFor(model => model.Prop2, new { #class = "control-label"})
#Html.ValidationMessageFor(model => model.Prop2)
</div>
</div>
</div>
<!-- This carries on similarly for lots more attributes -->
<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>
}
Inside the Beginform you should add #Html.HiddenFor(model => model.Something) where the Something are the properties which you want back on the postback.
If you don't then the property values will be default values.

Categories