Reputation: 6151
I have a simple model which models a vehicle entity. It has attributes: Model Make Colour RegistrationPlate
On the create View I want to users to be able to perform a server look up using the registration plate to auto fill the Model/Make/Colour information.
As such I'm trying to create an action link like so:
@Html.ActionLink("Look up registration", "RegLookup", "Vehicle", Model.Registration)
Where RegLookup is a get ActionResult method in the vehicle controller which goes away and finds the model/make/colour information based on the registration field passed through to it. The Make/Model/Colour information is retrieved from a separate database.
However at present on rendering the view - before even getting to the action link - an exception is thrown indicating that the Model is Null.
What I want to be passed through is effectively the value from the textbox representing the registration:
@Html.EditorFor(model => model.Registration)
How do I pass this value through?
Upvotes: 2
Views: 11629
Reputation: 218722
In your CreateView, typically your Model Properties should mostly be empty except some prepoulated values like dropdowns . What you should use is to use jQuery ajax to make an async call to an action method which returns the relevant data based on the registration plate and fill that in the Form
You may keep the action link like this
@Html.ActionLink("Look up registration", "RegLookup", "Vehicle",
new {@id="check"},null)
And attach a javascript function to the click event of it to make the ajax call
$(function(){
$("#check").click(function(e){
e.preventDefault();
var item=$(this);
var regPlateVal=$("#RegistrationPlate").val();
$.getJSON(item.attr("href")+"?registration="+regPlateVal,function(data){
if(data.Status=="success")
{
$("#Color").val(data.Color);
$("#Model").val(data.Model);
}
});
});
});
Assuming your RegLookUp
action method accept a parameter (With name registration
) and returns the data in JSON
format like below format
{
"Status": "success",
"Color": "Red",
"Model": "2011"
}
Upvotes: 3
Reputation: 14133
You need to do a normal POST or and AJAX one to send the plate number to the server. In your view, at design time you don't have the value the user entered.
Upvotes: 0
Reputation: 1038730
You need to pass the properties in the query string:
@Html.ActionLink(
"Look up registration",
"RegLookup",
"Vehicle",
new {
registration = Model.Registration
}
)
and then the controller action could take this registration
parameter:
public ActionResult RegLookup(string registration)
{
...
}
Upvotes: 0