Updating parent model on ajax call from partial view - ajax

I have a .net core application that has a page for changing settings. There is a visual representation of the page here:
https://i.imgur.com/R6MyDlo.png
This view (blue) contains a number of buttons (black) for changing tabs to display different settings pages. There is also a partial (red) that contains a number of other partials for the settings. This partial updates when switching between tabs or updating settings. Settings are not saved to the hardware or database until the user clicks save in the sidebar (green).
The settings come from a json file that can be several 100 kilobytes and are stored as an object in the view model. This view model is shared between all the partial views. When the user updates something it calls an ajax function sending the model as json. I have included an example for changing settings below but all follow a similar pattern.
Main view (blue):
#model Project.ViewModels.TestViewModel
<div class="row" id="body-row">
#Html.Partial("_SidebarPartial") // green
<div class="col">
<div class="row top-margin">
<div class="col-sm-12 col-md-12 col-lg-9">
<button id="generalButton" class="btn btn-primary mr-2 mb-2" onclick="LoadGeneral()">General</button>
#for (int i = 0; i < Model.Config.Machines.Count; i++)
{
<button id="#("Machine" + (i + 1))" class="btn btn-primary mr-2 mb-2" onclick="LoadMachine(#i)">
#Model.Config.Machines[i].Name
</button>
}
</div>
<div id="TestConfig" class="col-sm-12 col-md-6 col-lg-9">
#Html.Partial("Test/_ConfigPartial", Model) // red
</div>
</div>
</div>
</div>
Sample ajax call to update UI:
function UpdateMode(i, j) {
var viewModel = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
data = JSON.stringify({ mode: i, selectedProgram: j, model: viewModel })
$.ajax({
type: "POST",
data: data,
url: "https://localhost:44365/Test/UpdateMode",
contentType: "application/json"
}).done(function (res) {
$("#TestConfig").html(res)
});
}
Controller actions:
public IActionResult Config()
{
Model = new TestViewModel();
HttpContext.Session.SetObjectAsJson("Model", Model);
return View(HttpContext.Session.GetObjectFromJson<MachineViewModel>("Model"));
}
[HttpPost]
public PartialViewResult UpdateMode([FromBody]DtoTestModel model)
{
model.Model.Config.Programs[model.SelectedProgram].Mode = (ModeType) model.Mode;
HttpContext.Session.SetObjectAsJson("Model", model.Model);
return new PartialViewResult
{
ViewName = "~/Views/Shared/_GeneralPartial.cshtml",
ViewData = new ViewDataDictionary<TestViewModel>(ViewData, model.Model)
};
}
Temporary view model class. This is because [FromBody] only accepts one parameter and the updated model values are not posted to the server:
public class DtoTestModel
{
public TestViewModel Model { get; set; }
public int SelectedProgram { get; set; }
}
ViewModel:
public class TestViewModel
{
public Config TestConfig { get; set; }
public int Mode { get; set; }
public TestViewModel()
{
using (var reader = File.OpenText(#"temp\Config.txt"))
{
string json = reader.ReadToEnd();
TestConfig = JsonConvert.DeserializeObject<Config>(json);
}
}
}
Currently though the model stays the same throughout for the parent. So when a setting is updated it is only the changed version until the next setting change. I need a way to also update the parent model without refreshing the page.

Related

Ajax call breaks binding to object children

Without the ajax call, My main view binds to my parent class and the partial view on main view, binds to a child member of the parent class
parent...
public class Client
{
[ScaffoldColumn(false)]
public int Id { get; set; }
[DisplayName("Name")]
[Required]
[StringLength(120)]
public string Name { get; set; }
// etc...
public virtual Address Address { get; set; }
}
child of parent...
public class Address
{
[ScaffoldColumn(false)]
public int AddressId { get; set; }
[DisplayName("Address")]
[Required]
[StringLength(200)]
public string Street { get; set; }
// etc...
[ForeignKey("Client")]
public int? Id { get; set; }
public virtual Client Client { get; set; }
}
the main view
#using (Html.BeginForm("Create", "Client", FormMethod.Post, new Dictionary<string, object> { { "data-htci-target", "addressData" } }))
{
#Html.AntiForgeryToken()
<div class="row">
#Html.LabelFor(model => model.Name, new { #class = "control-label col-md-2" })
<div class="col-sm-4 col-md-4 col-lg-4">
#Html.Kendo().AutoCompleteFor(model => model.Name).HtmlAttributes(new { style = "width:100%" })
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
#{ var vdd = new ViewDataDictionary(ViewData) { TemplateInfo = new TemplateInfo() { HtmlFieldPrefix = "Address" } };}
#Html.Partial("_AddressPartial", Model.Address, #vdd)
// yada yada...you can imagine the rest of the very standard view
The partial view's model is Address and all hooks up.
When I post back to the server the Address member is properly filled with entered data from the partial view...
So now...in my partial view, I now load the js to call the async routine to load the IP GEO data for the user - so it pre-fills the city, province, country
Any example of an ajax call will suffice...mine calls an AddressControl, returns a partialview result and replaces a div named addressData with the updated partialview :
$(function() {
var urlGeoIeoip = "http://ip-api.com/json/?callback=?";
$.ajax({
url: urlGeoIeoip,
type: "GET",
dataType: "json",
timeout: 5000,
success: function (geoipdata) {
$.ajax({
url: "/getlocationdata/" + geoipdata.country + "/" + geoipdata.regionName + "/" + geoipdata.city,
type: "GET",
timeout: 5000,
success: function (data) {
//alert(data);
//var $form = $(this);
// var $target = $($form.attr("data-htci-target"));
var $newHtml = $(data);
//alert($target);
$("#addressData").replaceWith($newHtml);
$("#City").data("kendoComboBox").value(geoipdata.city);
$("#State").data("kendoComboBox").value(geoipdata.regionName);
$("#Country").data("kendoComboBox").value(geoipdata.country);
}
});
}
}).fail(function(xhr, status) {
if (status === "timeout") {
// log timeout here
}
});
});
All works great!
BUT
Now, when I post back to the user via the submit button, the Address child member of the parent class is null....
How do I get it to rebind the Address member of the parent class after return of the ajax call?
By generating your input fields in the partial view, the HTML helpers are unaware that your Address model is a property of your initial Client model, so it's generating HTML inputs like:
<input type="text" id="City" name="City" />
<input type="text" id="State" name="State" />
If your POST action method is accepting a Client model then the model binder will look for the properties City and State of the Client model, which don't exist.
You need your HTML input to look like:
<input type="text" id="Address_City" name="Address.City" />
<input type="text" id="Address_State" name="Address.State" />
Instead of using a partial for your Address fields, you should use an Editor Template which will then preserve the parent property as you need in this case.
#Html.EditorFor(x => x.Address)

MVC Knockout validation display and

I am using knockout for the first time and I am struggling to get my head around a problem.
I have a page with multiple sections and want to be able to edit a section and submit to the controller, then display the saved details.
Each section is a partial view which contains the display information and the form. They are shown and hidden as required. I have the code working for submitting, but the problem is when the ModelState is not valid. I need to return to the form with the validation message displayed
How can I display the form again when the server validation fails? When the validation fails it currently goes back to the display section.
Also I have noticed the validation message does not display.
I am sure this must be a common problem with a simple fix. I know there are knockout validation tools, but will need to do more complex business logic validation later on and need to get the technique working.
ViewModel:
[Required]
public DateTime? InterviewDate { get; set; }
View:
<div data-bind="if: showAdminInterviewDisplay" id="Display">
<div>
<button data-bind="click: showInterviewForm" id="EditButton">Edit</button>
</div>
<div>
#Html.Label("Inteview Date") :
<label data-bind="text: interviewDate"></label>
</div>
</div>
<div data-bind="if: showAdminInterviewForm" id="Form">
<div>
#Html.Label("Interview Date")
<input data-bind="value: interviewDate" id="interviewDatePicker" />
#Html.ValidationMessageFor(m => m.InterviewDate)
</div>
<div>
<button data-bind="click: saveInterviewDate">Submit</button>
</div>
Knockout ViewModel:
function InterviewViewModel() {
//Data
var self = this;
var jsonDate = #Html.Raw(Json.Encode(#Model.InterviewDate));
var date = new Date(parseInt(jsonDate.substr(6)));
self.interviewDate = ko.observable(dateFormat(date, "dd/mm/yyyy"));
self.showAdminInterviewDisplay = ko.observable(true);
self.showAdminInterviewForm = ko.observable();
self.showInterviewForm = function () {
self.showAdminInterviewDisplay(false);
self.showAdminInterviewForm(true);
$("#interviewDatePicker").datepicker({dateFormat: 'dd/mm/yy'});
};
//Operations
self.saveInterviewDate = function() {
$.ajax("#Url.Action("SaveInterview")", {
data: ko.toJSON(self),
type: "post",
contentType: "application/json",
success: function(data) {
self.showAdminInterviewDisplay(true);
self.showAdminInterviewForm(false);
}
});
};
};
ko.applyBindings(new InterviewViewModel());
Controller:
public ActionResult SaveInterview(KnockoutViewModel model)
{
if (ModelState.IsValid)
{
return Json(model);
}
return PartialView("_AdminInterview", model);
}
Instead of returning a Partial View from your Action Method, return a serialised error model to the success function in the AJAX call. The error model will contain all the errors in the ModelState.
See this post on how to get and consume the errors from Model State:
ASP.NET MVC How to convert ModelState errors to json (JK's answer)
So you would have something like:
Error Model:
public class JsonErrorModel
{
public JsonErrorModel()
{
HasFailed = true;
}
public bool HasFailed { get; set; }
public IEnumerable ErrorList { get; set; }
}
Controller:
if(ModelState.IsValid)
{
//Do whatever here
return Json(new { model });
}
return Json(new JsonErrorModel {ErrorList = ModelState.Errors()});
Success function of AJAX call:
success: function (result) {
if(result.HasFailed) {
self.showAdminInterviewDisplay(false);
self.showAdminInterviewForm(true);
DisplayErrors(result.ErrorList);
}
else {
self.showAdminInterviewDisplay(true);
self.showAdminInterviewForm(false);
}
}
So now, if the server side validation failed, the view will show the form and the validation errors.

Updating only the partial view contained in a mvc 3 page?

I have a MVC 3 page that returns a list of user responses with a partial view called "memo" (which displays/add memos) for each response. When I add a memo to a response, it should update the db and the list of memos for that response. It should be partial page update via ajax, which effects only the partial view "memo".
The view Response.chtml that contains "memo":
#using (Html.BeginForm("Response", "User", FormMethod.Post, new { id = "UserResponse" }))
{
.... code removed ....
#foreach (var response in Model)
{
<div class="qna"><input type="text" id=#response.responseId value="#response.ResponseText" />
<div>#Html.Partial("_memo", response.responseId)</div>
}
.....
The partial page "_memo.chtml":
<div>add memo</div>
<ul id="memos">
#foreach (var memo in Model) {
<li>#memo.Text</li>
}
</ul>
<form method="post" id="memoForm"
action="#Url.Action("AddMemo")">
#Html.TextArea("Memo", new { rows = 5, cols = 50 })
<br />
<input type="submit" value="Add" />
</form>
Controller for view User/Response:
[HttpGet]
public ActionResult Response(id)
{
.....
return View(responses);
I just started with the code above, need help filling the blanks.
If I pass the response Id to the partial view, how do I pull the list of memos for that response? Will it involve ajax? (instead of ..Partial("_memo", response.memos))
How do I update the partial view via ajax call. What is ajax call (sample code) on the client side and how would the controller look? When the ajax call is successful, how do I update the list memos div="memos" to reflect the new memo?
Will the form action from Response conflict with form action of the partial view Memo?
Answers to Questions:
You shouldn't pass the responseId to the partial, you should pass the memo collection from your response object and make your partial view strongly typed to that collection.
See full code example below.
You don't need the form in the partial since you're making a simple ajax call to add the new memo. See full code example below.
This is a modified example from a project I am currently working on:
There is a bit of code to follow, so here goes:
This is my model. There are several sections on a career planning form, one of which is a section to select and update competencies. The SelectCompetencies model has a collection of competencies within it. The user will have the ability to add competencies. When they do, it will be added to the database and will update the list of competencies in the partial.
public class CareerPlanningFormViewModel
{
// code removed ...
public SelectCompetenciesModel SelectCompetencies { get; set; }
// code removed ...
}
public class SelectCompetenciesModel
{
public int CareerPlanningFormID { get; set; }
public IList<CompetencyModel> Competencies { get; set; }
public byte MaximumCompetenciesAllowed { get; set; }
}
public class CompetencyModel
{
public int CompetencyID { get; set; }
public int? CompetencyOptionID { get; set; }
public string ActionPlan { get; set; }
public IDictionary<int, string> CompetencyOptions { get; set; }
}
The main view of the career planning form: /Views/CPF/CareerPlanningForm.cshtml
#model MyNamespace.Models.CareerPlanningForm.CareerPlanningFormViewModel
<link rel="stylesheet" href="#Url.Content("~/Content/CreateCPF.css")" />
#using (Html.BeginForm())
{
// other sections loaded here...
// code removed for brevity...
#Html.Partial("SelectCompetencies", Model.SelectCompetencies)
// other sections loaded here...
// code removed for brevity...
}
The SelectCompetencies partial: /Views/CPF/SelectCompetencies.cshtml
The user will fill in the new action plan text and click the add competency button.
That will post via ajax to CPFController/NewCompetencyTemplate
#model MyNamespace.Models.CareerPlanningForm.SelectCompetenciesModel
#Html.HiddenFor(m => m.CareerPlanningFormID)
<h3>Select Competencies</h3>
<p class="guidance">
Select up to #Model.MaximumCompetenciesAllowed competencies to focus on improving.
</p>
<table id="CompetenciesTable">
<thead>
<tr>
<th>Competency</th>
<th>Action Plan:</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.Competencies.Count(); i++)
{
#Html.EditorFor(m => m.Competencies[i])
}
</tbody>
<tfoot id="CompetenciesTableFooter" class="#(Model.Competencies.Count() < Model.MaximumCompetenciesAllowed ? "" : "hidden")">
<tr>
<td colspan="2">
#Html.TextArea("NewActionPlanText")
#Html.Button(ButtonType.Button, "Add Another Competency", "add", new { id = "AddCompetencyButton" })
</td>
</tr>
</tfoot>
</table>
#section script
{
<script>
jQuery(document).ready(function ($) {
var competenciesTableBody = $('#CompetenciesTable tbody'),
competenciesTableFooter = $('#CompetenciesTableFooter'),
addCompetencyButton = $('#AddCompetencyButton'),
newCompetencyTemplateUrl = '#Url.Content("~/CPF/NewCompetencyTemplate")',
count = competenciesTableBody.find('tr').length,
newActionPlanText = $('#NewActionPlanText'),
careerPlanningFormID = $('#CareerPlanningFormID');
addCompetencyButton.click(function () {
$.ajax({
url: newCompetencyTemplateUrl(),
type: 'POST',
data: {
careerPlanningFormID: careerPlanningFormID,
actionPlan: newActionPlanText,
itemCount: count
},
dataType: 'html',
success: function (data) {
var elements = $(data);
// other code removed here...
competenciesTableBody.append(elements);
// other code removed here...
}
});
});
});
</script>
}
Views/CPF/EditorTemplates/CompetencyModel.cshtml
#model MyNamespace.Models.CareerPlanningForm.CompetencyModel
<tr class="competency">
<td>
#Html.DropDownListFor(m => m.CompetencyOptionID, new SelectList(Model.CompetencyOptions, "Key", "Value"), "Select competency...")
</td>
<td>
#Html.TextAreaFor(m => m.ActionPlan, new { #class = "competencyActionPlan" })
#Html.HiddenFor(m => m.CompetencyID)
</td>
</tr>
The controller containing the action to add the new competency: /Controllers/CPFController.cs
This will call the CareerPlanningFormService to add the new competency and will return a partial view for NewCompetencyTemplate that will render out the new competency
public class CPFController : Controller
{
private readonly ICareerPlanningFormService careerPlanningFormService;
public CPFController(ICareerPlanningFormService careerPlanningFormService)
{
this.careerPlanningFormService = careerPlanningFormService;
}
[HttpPost]
public PartialViewResult NewCompetencyTemplate(int careerPlanningFormID, int itemCount, string newActionPlanText)
{
var count = itemCount + 1;
// Even though we're only rendering a single item template, we use a list
// to trick MVC into generating fields with correctly indexed name attributes
// i.e. Competencies[1].ActionPlan
var model = new SelectCompetenciesModel
{
Competencies = Enumerable.Repeat<CompetencyModel>(null, count).ToList()
};
model.Competencies[count - 1] = this.careerPlanningFormService.BuildNewCompetencyModel(careerPlanningFormID, newActionPlanText);
return this.PartialView(model);
}
}
My service class: CareerPlanningFormService.cs
This handles the business logic and makes the calls to the repository to add the item to the database and returns a new CompetencyModel
public class CareerPlanningFormService : ICareerPlanningFormService
{
private readonly IMyRenamedRepository repository;
private readonly IPrincipal currentUser;
public CareerPlanningFormService(
IMyRenamedRepository repository,
IPrincipal currentUser)
{
this.repository = repository;
this.currentUser = currentUser;
}
public CompetencyModel BuildNewCompetencyModel(int careerPlanningFormID, string newActionPlanText)
{
var competency = new Competency
{
CareerPlanningFormID = careerPlanningFormID,
CompetencyOptionID = null,
ActionPlan = newActionPlanText
};
this.repository.Add(competency);
this.repository.Commit();
return new CompetencyModel
{
CompetencyID = competency.CompetencyID,
CompetencyOptionID = competency.CompetencyOptionID,
ActionPlan = competency.ActionPlan,
CompetencyOptions = this.GetCompetencyOptionsForCareerPlanningFormID(careerPlanningFormID)
};
}
}
Now, the partial for NewCompetencyTemplate: Views/CPF/NewCompetencyTemplate.cshtml
This is very simple, it simply renders the same editor template as above, for the last competency in the collection (which we just added)
#model MyNamespace.Models.CareerPlanningForm.SelectCompetenciesViewModel
#Html.EditorFor(m => m.Competencies[Model.Competencies.Count() - 1])
When the ajax call succeeds, it will receive this partial back from the controller action method it called. It then takes the partial and appends it to the competencies table body
// snippet from ajax call above
competenciesTableBody.append(elements);
I hope this helps. Let me know if you have any additional questions.
While you're correct that you can do it just by returning a partial view containing the updated content, you may also consider using jQuery's load method.
Look here, in particular at the "loading page fragments" section. Basically you can just get the original page again and jQuery will "extract" the content you want as long as it can be targetted by a selector (such as a div id).
Note, this solution is not suitable in all cases as there will be redundant markup in the response from the server because you will be discarding the rest of the page content and just using the updated part.

Sending new order back to MVC controller

using the JQuery sortable, and trying to send the new order back to my controller, but not having a whole lot of luck. My view is:
using (Ajax.BeginForm("EditTickerOrder", new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "POST", }))
{
<div id="editableticker">
#Html.HiddenFor(m => m.ProjectGUID)
<ul id="sortablediv">
#foreach (DGI.CoBRA.Tools.BussinessObjects.CollabLibrary.TickerObjects.Ticker t in Model)
{
<li class="ui-state-default" id="#t.pKeyGuid.ToString()">
<p>#Html.CheckBox(t.pKeyGuid.ToString(), t.Display, new { #class = "activechk" })
<span style="font-weight: bold">
#t.Text
</span>
</p>
</li>
}
</ul>
<input type="submit" value="Save New Ticker Order" />
}
and my controller is:
[HttpPost]
public ActionResult EditTickerOrder(Guid ProjectGUID, List<string> items)
{
TickerCollectionModel TickerData = new TickerCollectionModel();
TickerData.ProjectGUID = ProjectGUID;
TickerData.ListAllBySession(ProjectGUID);
return PartialView("TickerList", TickerData);
}
yet the list<string> items is always null. Any ideas?
You are writing foreach loops, most definitely violating the naming conventions for your form input fields that the default model binder expects for working with collections. If you don't respect the established wire format, you cannot expect the default model binder to be able to rehydrate your models in the POST action.
In fact, why don't you use view models and editor templates? They make everything trivial in ASP.NET MVC.
So let's define a view model that will reflect your view requirements (or at least those shown in your question => you could of course enrich it with additional properties that you want to handle):
public class TickerViewModel
{
public Guid Id { get; set; }
public bool IsDisplay { get; set; }
public string Text { get; set; }
}
public class ProjectViewModel
{
public Guid ProjectGUID { get; set; }
public IEnumerable<TickerViewModel> Tickers { get; set; }
}
and then a controller whose responsibility is to query your DAL layer, retrieve a domain model, map the domain model into the view model we defined for this view and pass the view model to the view. Inversely, the POST action receives a view model from the view, maps the view model back into some domain model, passes the domain model to your DAL layer for processing and renders some view or redirects to a success action:
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: those values come from a data layer of course
var model = new ProjectViewModel
{
ProjectGUID = Guid.NewGuid(),
Tickers = new[]
{
new TickerViewModel { Id = Guid.NewGuid(), Text = "ticker 1" },
new TickerViewModel { Id = Guid.NewGuid(), Text = "ticker 2" },
new TickerViewModel { Id = Guid.NewGuid(), Text = "ticker 3" },
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(ProjectViewModel model)
{
// Everything will be correctly bound here => map the view model
// back into your domain model and pass the domain model to
// your DAL layer for processing ...
return Content("Thanks for submitting");
}
}
a view (it is worth noting that in this example I have used a standard form instead of AJAX but it is trivial to convert it into an AJAX form):
#model ProjectViewModel
#using (Html.BeginForm())
{
#Html.HiddenFor(m => m.ProjectGUID)
<div id="editableticker">
<ul id="sortablediv">
#Html.EditorFor(x => x.Tickers)
</ul>
</div>
<button type="submit">OK</button>
}
and finally the corresponding editor template which will automatically be rendered for each element of the Tickers collection (~/Views/Home/EditorTemplates/TickerViewModel.cshtml):
#model TickerViewModel
<li class="ui-state-default">
<p>
#Html.CheckBoxFor(x => x.IsDisplay, new { #class = "activechk" })
#Html.LabelFor(x => x.IsDisplay, Model.Text)
#Html.HiddenFor(x => x.Text)
#Html.HiddenFor(x => x.Id)
</p>
</li>

Performing create operations on two models via one action

I have two models : Category and Picture which refers to two tables, Categories and Pictures respectively. The Category model has a navigation property to Picture model.
Now, I created a controller using Scaffolding feature with CRUD operations for Category. Following is the code :-
public ActionResult Create()
{
ViewBag.ParentCategoryId = new SelectList(db.Categories, "Id", "Name");
ViewBag.PictureId = new SelectList(db.Pictures, "Id", "PictureUrl");
return View();
}
The automatically generated controller actions uses SelectList for listing the available Picture entries in the database and passes it down to dropdownlist for selection. This is not the ideal scenario since what I want is to unable the user to upload the Picture and then the reference is added to Category model. Later, the entries are saved to Categories and Pictures table.
Create model like this:
public class FullCategoryModel
{
public HttpPostedFileBase Picture { get; set; }
public Category CategoryModel {get; set;}
}
In view:
#using (Html.BeginForm("Create", "Category", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(model => model.Category.Name) // example, put there all category details
<input type="file" name="Picture" id="Picture" />
<input type="submit" value="Upload" />
}
Then create action:
[ActionName("Create")]
[HttpPost]
public ActionResult Create(FullCategoryModel model)
{
// here you can get image in bytes and save it in db,
// also all category detail are avalliable here
MemoryStream ms = new MemoryStream();
model.Picture.InputStream.CopyTo(ms);
Image picture = System.Drawing.Image.FromStream(ms);
// save in db as separate objects, than redirect
return RedirectToAction("Index", "Category");
}
First of all, I would like to thank #NickLarsen for making me believe that my understanding is good and i can achieve the task myself.
The problem was not that too tough but since i was new to Asp.net MVC, things were bit baffling. From the very start, I had the notion that i will be needing a ViewModel merging Category and Price classes and then a picture uploading API. But, somehow I wasn't able to fit the pieces in right place. Therefore after various regression and research over the internet, I achieved the task in following manner :-
First of all, I created a ViewModel
public class CatPicView
{
public Category Category { get; set; }
public Picture Picture { get; set; }
}
Second, I added the Uploadify javascript API
<script type="text/javascript">
$('#file_upload').uploadify({
'uploader': '#Url.Content("~/uploadify/uploadify.swf")',
'script': '#Url.Action("Upload", "Category")',
'cancelImg': '#Url.Content("~/uploadify/cancel.png")',
'buttonText': 'Upload',
'folder': '#Url.Content("~/content/images")',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
'auto': true,
'onComplete': function (event, ID, fileObj, response, data) {
var json = jQuery.parseJSON(response);
$("#pictureImage").html("<img src='"+json+"' alt='"+json+"' height='100px' width='100px'/>");
$("#Picture_PictureUrl").val(json);
$("#pictureRemove").show();
}
});
</script>
Hooked the API to following Server Function for renaming and saving to folder
[HttpPost]
public ActionResult Upload(HttpPostedFileBase fileData)
{
if (fileData != null && fileData.ContentLength > 0)
{
//var fileName = Server.MapPath("~/Content/Images/" + Path.GetFileName(fileData.FileName));
int pictureCount = 800000;
pictureCount += db.Pictures.Count();
string extension = Path.GetExtension(fileData.FileName);
string renamedImage = Server.MapPath("~/Content/Images/Categories/cat" + pictureCount + extension);
fileData.SaveAs(renamedImage);
return Json("/Content/Images/Categories/" + Path.GetFileName(renamedImage));
}
return Json(false);
}
And at last, rewrote the Category create Function as below for saving changes to DB
[HttpPost]
public ActionResult Create(CatPicView catPic)
{
if (ModelState.IsValid)
{
if (!String.IsNullOrEmpty(catPic.Picture.PictureUrl))
{
Picture picture = new Picture();
picture.PictureUrl = catPic.Picture.PictureUrl;
db.Pictures.Add(picture);
catPic.Category.PictureId = picture.Id;
}
db.Categories.Add(catPic.Category);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
I think MVC scaffolding feature see the relation of two models as "Many to Many". That's why it created two drop down list for you. According to your scenario, you could do "Category" create page without "Picture" model data because "Picture" is the main entity here. So In the picture create action.
[HttpPost]
public ActionResult Create(Picture picture)
{
if (ModelState.IsValid)
{
databaseContext.Pictures.Add(picture);
databaseContext.SaveChanges();
return RedirectToAction("Index");
}
return View(picture);
}
In the view page of create picture
#model YourProjectName.Models.Picture
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Picture</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Url)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Url)
#Html.ValidationMessageFor(model => model.Url)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Categories.CategoryID, "Category")
</div>
<div class="editor-field">
#Html.DropDownList("CategoryID", "Choose Category")
#Html.ValidationMessageFor(model => model.Categories.CategoryID)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}

Resources