Hi all,
New to MVC development. Struggling to load a partial view for 'Create' with prepopulated field values from Parent View.
Basically I have a main View, and within the Main view I have a partial view which displays a grid with Edit button and Add button.
This is how I am loading my Partial view in my Parent view.
var url = '@Url.Action("Index", "MyModel")';
$.ajax({
url: url ,
type: "get",
success: function (data) {
$('#partialPlaceHolder').html(data);
$('#partialPlaceHolder').fadeIn('fast');
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
The Edit button loads the 'Edit' View and the Add button loads the 'Create' view, pretty standard MVC.
But now my main issue is, I want to prepopulate the 'Create' view when 'Add' button is clicked with values from the Parent View. So the users dont have to input the values into them again.
My model consists of 3 items
public class MyModel
{
public int ID { get; set; }
[DisplayName("My Note")]
[Required(ErrorMessage = "Note cannot be left blank.")]
public string MyNote { get; set; }
[DisplayName("My Value")]
[Required(ErrorMessage = "Value is required")]
[StringLength(12, MinimumLength = 12)]
public string MyValue { get; set; }
[DisplayName("My List")]
[Required(ErrorMessage = "Please select an item.")]
public int MyList{ get; set; }
public virtual MyListModel MyLists { get; set; }
}
When the Add button is clicked, I want the 'Create' view to pre populate the 'My Value' and 'My List' item from the Parent View and populate the 'create' view when its loaded. So the user would only have to fill in the 'My notes' text box and click on 'Create' button to save the changes. Is something like this possible? Any help would be appreciated.
Below is the Action result code in my - Create Controller.
What I have tried:
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Create(MyModel mymodel)
{
try
{
if (ModelState.IsValid)
{
try
{
db.MyModel.Add(mymodel);
db.SaveChanges();
ViewBag.MyList = new SelectList(db.MyList, "ID", "MyText", mymodel.MyList);
return Json(new { success = true });
}
catch (Exception e)
{
throw e;
}
}
return Json(new
{
success = false,
responseText = ModelState.Keys.SelectMany(k => ModelState[k].Errors)
.Select(m => m.ErrorMessage).ToList()
});
}
catch (Exception ex)
{
return Json(new { success = false, responseText = "Error creating new note. " + ex.Message });
}
}